ReactJS——检测状态变化的问题

ReactJS — problems with detecting changes in state

查看此示例:http://codepen.io/lzhelenin/pen/jVbeRg

有一个小的 React 应用程序,它的初始状态看起来是这样的:

{
  foo: 123,
  bar: [{
    cux: 456
  }]
}

如果您按下按钮,它会在 state.bar 中添加一个新对象并更改 state.foo 值。但是,如果您按下它并在那之后查看控制台,您会看到先前状态的 state.bar 与新状态的 state.bar 完全相同,尽管 state.foo 不同.为什么会这样?

来自http://underscorejs.org/#clone

clone_.clone(object) Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.

因此,prevState.barthis.state.bar,您要将新值推入其中,它们都是对同一数组的引用。

如@Radio- 所述,_.clone 创建了一个 浅拷贝克隆 ,因此 prevcurr 状态都是引用同一个数组,所以你最好调整你的 clickHandler() 方法是这样的:

  clickHandler() {
    this.setState({
      foo: 999,
      bar: [
        ...this.state.bar,
        {cux: 123}
      ]
    });
  }