【发布时间】:2018-07-21 21:13:29
【问题描述】:
我想我在这里遗漏了一个关于 React 和 Redux 的概念。我正在尝试处理存储在 redux 中的对象,但遇到了麻烦。
还原: 我有一个动作 fetchItems,它从数据库中获取所有项目。此操作成功。
反应: 我有一个容器 UserProfile,它在 componentDidMount 中调用 fetchItems。
class UserProfile extends Component {
componentWillMount() {
console.log('------------ USER PROFILE -------------------');
}
componentDidMount() {
console.log('[ComponentDidMount]: Items: ', this.props.items);
this.props.fetchItems();
}
render() {
let profile = null;
console.log('[Render]: Items: ', this.props.items);
return <Auxillary>{profile}</Auxillary>;
}
}
const mapStateToProps = state => {
return {
items: state.items.items
};
};
const mapDispatchToProps = dispatch => {
return {
fetchItems: () => dispatch(actions.fetchItems())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UserProfile);
我看到的问题是 this.props.items 始终为空(即使 fetchItems 成功)。我可以检测到项目存储在 redux 存储中的唯一方法是使用 componentWillRecieveProps(nextProps)。在这里,我成功看到了 nextProps 中的项目。我觉得使用 componentWillReceiveProps 可能太“杂乱”了。我想我要问的是,在 react 中处理 redux 状态更新的标准方法是什么?
阿塞尔
【问题讨论】:
-
一个组件的生命周期如下:
constructor() componentWillMount() render() componentDidMount()所以在componentDidMount()中执行的任何东西都会在render()之后得到执行者
标签: reactjs redux react-redux react-lifecycle