我正在使用 React (14.2) 和 Redux。我已完成所有设置并正常工作,除非我在更新时分派(dispatch)操作时,会发生递归循环。
componentWillMount() {
const { wizardActions, valid, errors } = this.props
wizardActions.setPropState({valid: valid, errors: errors})
}
componentWillUpdate(nextProps) {
const { wizardActions } = this.props
console.log('NP', nextProps)
//*** IF I UNCOMMENT THE FOLLWOING LINES THE APP GOES INTO AN INFINTIE
// RECURSION LOOP...
/*if(this.props !== nextProps) {
wizardActions.setPropState({valid: nextProps.valid, errors: nextProps.errors})
}*/
}
当当前组件的 props 发生变化时,如何更新 Redux 状态?我还在 componentWillReceiveProps()
中尝试过,它也做了同样的事情。
TIA!
最佳答案
当这些变化是由外部原因引起时,例如,可以调度操作来响应 Prop 更改。 react 路由器。但您似乎想要调度操作来响应从 Redux 本身注入(inject)的 props 的更改,这使得它循环。这实际上不是您应该在 Redux 中做的事情。
有效
和错误
从何而来?如果它们由 Redux 管理,则无需在 componentWillUpdate
中分派(dispatch)操作 - 当您收到新值时,它们已经在 Redux 状态中更新。如果它们由具有本地状态的父组件管理,请考虑首先将该状态移动到 Redux,而不是使用两个事实源(组件和存储)复制它。
一般来说,您的应用中的任何给定状态都应该只有一个事实来源。这个事实来源可以是 Redux 存储、React 组件或某些外部来源,但您不应该尝试在生命周期方法中同步多个事实来源。
关于javascript - 更新时的 React Redux 调度会导致递归错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36649288/