我在这里阅读文档
https://github.com/reactjs/react-redux/blob/master/docs/api.md
我想尽可能多地使用无状态组件,但我无法弄清楚我将如何处理初始数据有效负载.使用Stateful React组件,My容器和组件将显示:
// Container
const mapDispatchToProps = (dispatch) {
return {
fetchData: () => dispatch(fetchDataAction());
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
// Component
class MyComponent extends React.Component {
componentDidMount() {
this.props.fetchData();
}
}
如果我使组件无状态,componentDidMount的逻辑会在哪里?
我已经看过一些示例,他们建议您使用有状态的React在容器中扩展无状态组件,并在那里添加该逻辑:
// Container
class MyComponentContainer extends MyComponent {
componentDidMount() {
this.props.fetchData();
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MyComponentContainer);
但这是最好的方法吗?如果我很想创建一个有状态反应,为什么不直接在MyComponent上做呢?
编辑只是为了清楚;我问我是否可以基本上加载我的初始数据,而无需在任何地方创建React.Component.
最佳答案 与您的主要问题相关:是的,您可以在创建商店后立即加载数据.只需在代码中的任何位置使用store.dispatch,甚至在React.Components之外.
您可以检查simple example here.如您所见,组件和数据加载过程完全相互分离.
But is that a best way to do it? If I am bothering to create a Stateful React, why not just do it directly on MyComponent?
事实上,我没有任何理由去做你在片段中提供的内容.更重要的是,从React.Component继承你的组件绝对是React世界的气味.