【问题标题】:React Redux dispatch on update causes recursion errorReact Redux dispatch on update 导致递归错误
【发布时间】:2016-04-15 14:01:58
【问题描述】:

我正在使用 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!

【问题讨论】:

  • 使用if 声明?当然你只想在特定情况下更新后发送,例如this.props !== nextProps
  • 添加了 if 语句,但行为仍然相同
  • 哦,这不可能是 exact if 语句,因为对象引用总是不同的.. 总是会评估为 true。您必须比较您想要成为新的道具中的特定值。

标签: javascript reactjs redux react-redux


【解决方案1】:

当 prop 更改是由外部因素引起时,可以调度 action 以响应 prop 更改,例如反应路由器。但似乎您想要调度操作以响应对从 Redux 本身注入的 props 的更改,这使其循环。这不是你在 Redux 中真正应该做的事情。

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

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

【讨论】:

    【解决方案2】:

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

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

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

    1. 感谢所有回复和其中一些的详细程度... 是 @azium 引导我找到了可行的解决方案
    2. ComponentDidUpdate 更适用于 DOM 操作,这不是我在这里所做的
    3. 关注的道具(有效和错误)由 Redux 表单装饰器注入。 Redux Form 确实将一些东西保持在 Redux 状态,但不是这些 - 它们实际上是注入的运行时道具

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • componentDidUpdate 是针对 DOM 操作而设计的,这不是这里所做的
      猜你喜欢
      • 2017-04-21
      • 2021-03-03
      • 2011-05-16
      • 1970-01-01
      • 2021-09-07
      • 2021-08-15
      • 1970-01-01
      • 2022-12-14
      • 2012-05-08
      相关资源
      最近更新 更多