首页 文章

更新时React Redux调度导致递归错误

提问于
浏览
1

我正在使用React(14.2)和Redux . 我已经设置好所有工作,除非我在更新时调度操作,否则会发生递归循环 .

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!

3 回答

  • 2

    有没有理由不能使用 componentDidUpdate 钩子?
    React docs中,他们注意到不要在 componentWillUpdate 中调用 this.setState 以避免无限循环 . Redux的 dispatch 不是 this.setState ,但它会产生相同的效果 .

  • -1

    当那些由外部事物引起时,可以响应于道具变化而发送动作,例如,反应路由器 . 但似乎你想要调度动作以响应从Redux本身注入的道具的变化,这使得它是循环的 . 这不是你应该在Redux中做的事情 .

    validerrors 来自哪里?如果它们由Redux管理,则无需在 componentWillUpdate 中调度操作 - 在您收到新值时,它们已在Redux状态下更新 . 如果它们由具有本地状态的父组件管理,请考虑首先将该状态移动到Redux,而不是使用两个事实来源(组件和存储)复制它 .

    一般来说,应用程序中任何给定状态应该只有一个事实来源 . 这个事实来源可以是Redux存储,React组件或某些外部源,但您不应该尝试在生命周期方法中同步多个事实来源 .

  • 0

    好的 - 为了让这个工作没有问题,我将 if 修改为prop propc,如下所示:

    componentWillUpdate(nextProps) {
      const { wizardActions } = this.props
      if(this.props.errors !== nextProps.errors) {
        wizardActions.setPropState({valid: nextProps.valid, errors: nextProps.errors})
      }
    }
    

    还有一些事情......

    • 感谢所有回复和其中一些细节的详细程度... @zium引导我走上一条有效的解决方案之路

    • ComponentDidUpdate更适用于DOM操作,这不是我在这里做的

    • 关注的道具(有效和错误)由Redux Form装饰器注入 . Redux Form确实保留了一些处于Redux状态的东西,但不是这些 - 它们实际上是注入运行时道具

相关问题