Lzhelenin Lzhelenin - 1 month ago 11
Javascript Question

ReactJS — problems with detecting changes in state

Checkout this example: http://codepen.io/lzhelenin/pen/jVbeRg

There's a small React application, it's initial state looks that way:

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


If you press the button, it adds a new object in state.bar and changes state.foo value. However if you press it and take a look at console after that, you'll see that state.bar of the previous state is exactly the same as state.bar of the new state despite state.foo is different. Why does it happen?

Answer

As @Radio- mentioned, _.clone create a shallow-copied clone, so both the prev and curr state are both refer to the same array, so you better adjust your clickHandler() method to be like this:

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