0

I did not know what to do with the keywords, so I could not check for duplicate questions.

Yesterday I opened the inside of react.js and looked at ReactComponent.prototype.setState. At the top of the function, there was the following statement in the description.

When a function is provided to setState, it will be called at some point in the future (not synchronously). It will be called with the up to date component arguments (state, props, context). These values can be different from this.* because your function may be called after receiveProps but before shouldComponentUpdate, and this new state, props, and context will not yet be assigned to this.

It seems that the entire context is that when I write a callback function, this.* may be different from what I expected at some point in the future, and it is not drawn to my mind specifically about what happens.

If possible, I would be grateful if you could give me a simple example.

Jason Park
  • 127
  • 2
  • 9

1 Answers1

1

It means that when you're inside a setState callback state, props and context are not guaranteed to be the same objects you'd find at this.state, this.props and this.context. E.g.

this.setState((state, props, context) => {
  this.state === state // false
  this.props === props // false
  this.context === context // false
})

In other words, don't reach for any objects outside of what the setState callback passes you as arguments.

Jed Richards
  • 12,244
  • 3
  • 24
  • 35