0

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?

2 Answers 2

1

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}
      ]
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

1

From 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.

So, prevState.bar and this.state.bar, which you're pushing new values into, are both references to the same array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.