Lzhelenin Lzhelenin - 1 year ago 80
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 Source

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() {
      foo: 999,
      bar: [
        {cux: 123}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download