2016-04-15 35 views
1

我正在使用React(14.2)和Redux。除了当我在update上分配一个动作时,我有一切设置和工作,发生递归循环。React 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}) 
    }*/ 
} 

如何在当前组件的道具更改时更新Redux状态?我也在componentWillReceiveProps()中试过这个,它也做了同样的事情。

TIA!

+1

使用'if'语句?当然,你只想在具有特定情况的更新后调度,比如'this.props!== nextProps' – azium

+0

添加了if语句,但仍然是相同的行为 –

+3

哦,它不能是* exact * if语句,因为对象引用是总是不同的..这将永远评估为真。你必须比较你想成为新的道具内的特定值。 – azium

回答

-1

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

+0

componentDidUpdate面向DOM操作,这不是在这里完成的 –

2

当由外部事件引起的派送动作以响应道具变化即可。反应路由器。但似乎你想分发动作以响应从Redux注入的道具的变化,这使得它变得循环。这在Redux中并不是你应该做的。

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

一般来说,应用程序中的任何给定状态应该只有一个事实根源。这个真相的来源可以是一个Redux商店,一个React组件或一些外部来源,但是你不应该尝试在生命周期方法中同步几个真相来源。

0

OK - 得到这个工作没有问题,我修改了if是道具specifc如下:

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状态下保留了一些东西,但不是这些 - 它们被直接注入了运行时支持