【问题标题】:shouldComponentUpdate won't receive the newest stateshouldComponentUpdate 不会收到最新状态
【发布时间】:2015-11-14 08:25:00
【问题描述】:

我使用Reflux.connect 方法更改组件状态,但我无法获得shouldComponentUpdatenextStatethis.state 之间的不同部分。实际上,this.state 已经有了我期望在调用 shouldComponentUpdate 时出现在 nextState 中的新值。

当我想将 shouldComponentUpdate 与 Reflux 一起使用时,我需要做什么?

  var component = React.createClass({
     mixins: [Reflux.connect(store1, 'store1data'),
              Reflux.connect(store2, 'store2data')],

     shouldComponentUpdate: function(nextProps, nextState) {
        //Here this.state.store1data is equal to nextState.store1data
     }

【问题讨论】:

    标签: refluxjs


    【解决方案1】:

    确保您没有改变状态,而是返回它的新副本。如果您的商店只更改状态内的字段,则this.state 指针已经指向变异状态。

    所以在你的 store1 中,而不是:

    store1Data.someKey = newValue;
    this.trigger(store1Data)
    

    尝试做:

    store1Data = _.assign({}, store1Data, {someKey: newValue}); // this uses lodash, for example
    this.trigger(store1Data)
    

    这样每次更改时您都会获得 store1Data 的新副本。

    在处理状态时,不变性是一个重要的概念,尤其是在 React/Flux 中,因为它允许您快速确定状态是否已更改。尝试养成在更改状态时始终返回新副本的习惯,并且永远不要更改状态内的任何内容,除非您先克隆它。

    Immutablity in React
    ImmutableJs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 2019-05-07
      • 2021-10-17
      • 1970-01-01
      相关资源
      最近更新 更多