Reactjs componentDidMount中一行中的2个操作在React/Redux中不同步工作?
我在componentDidMount中有两个操作: 操作1使用虚拟数据启动状态。 操作2过滤状态。 但是当动作2发生时,由于某种原因,动作1还没有运行,因此没有什么可过滤的 如果我在操作2上设置超时,它可以解决问题,但这不是一个好的解决方案 代码如下:Reactjs componentDidMount中一行中的2个操作在React/Redux中不同步工作?,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我在componentDidMount中有两个操作: 操作1使用虚拟数据启动状态。 操作2过滤状态。 但是当动作2发生时,由于某种原因,动作1还没有运行,因此没有什么可过滤的 如果我在操作2上设置超时,它可以解决问题,但这不是一个好的解决方案 代码如下: componentDidMount() { const filterBy = this.props.collection.filterBy // Action 1 this.props.collectionActio
componentDidMount() {
const filterBy = this.props.collection.filterBy
// Action 1
this.props.collectionActions.loadRandomItems()
if (this.props.page == 'my-items') {
console.log(this.props.collection.items)
// Action 2
this.props.collectionActions.filter({ ...filterBy, amOwner: true}, this.props.collection.items)
}
}
请注意,console.log显示的是一个空数组,但操作1应该已将项目加载到此数组,以便操作2可以使用它。好的,在这个.props.collectionActions.loadRandomItems之后,您的存储确实会更新。问题是您的组件需要重新渲染以获得新的道具。这意味着在您的组件中,DidMount这个道具指向相同的旧版本道具。componentDidMount不是处理道具更新的好地方。使用组件将接收道具
我想补充一点,将过滤代码移到组件之外将有助于消除一些复杂性,这样您就可以传入准备好显示的道具。因为您使用的是react-redux,所以mapStateToProps将是一个很好的地方。
componentDidMount() {
// Action 1
this.props.collectionActions.loadRandomItems()
}
componentWillReceiveProps(newProps) {
if (newProps.page == 'my-items') {
// Action 2
const filterBy = newProps.collection.filterBy
newProps.collectionActions.filter({ ...filterBy, amOwner: true}, this.props.collection.items)
}
}