目标:加载 react-router 路由时,调度 Redux 操作,请求异步Saga工作器为该路由的底层无状态组件获取数据。
问题:无状态组件只是函数,没有生命周期方法,例如 componentDidMount,所以我不能(?)从函数内部调度 Redux 操作。
我的问题部分与将有状态 React 组件转换为无状态功能组件有关:如何实现“componentDidMount”类型的功能?,但我的目标只是调度一个请求将数据异步填充到商店的 Redux 操作(我使用 Saga,但我认为这与问题无关,因为我的目标只是调度一个普通的 Redux 操作),然后由于更改了数据属性,无状态组件将重新渲染。
我正在考虑两种方法:要么使用react-router 的某些功能,要么使用Redux 的connect方法。是否有所谓的“react方式”来实现我的目标?
编辑:到目前为止,我想出的唯一解决方案是在 mapDispatchToProps 中分派动作,如下所示:
const mapStateToProps = (state, ownProps) => ({
data: state.myReducer.data // data rendered by the stateless component
});
const mapDispatchToProps = (dispatch) => {
// catched by a Saga watcher, and further delivered to a Saga worker that asynchronically fetches data to the store
dispatch({ type: myActionTypes.DATA_GET_REQUEST });
return {};
};
export default connect(mapStateToProps, mapDispatchToProps)(MyStatelessComponent);
然而,这似乎有些肮脏,而不是正确的方法。