React - Functional setState (previous state) different from new updated value?

点点圈 提交于 2019-12-04 10:53:38

If your new state is calculated based on any value which is already in state - then you should use the second form of setState where you use a function:

this.setState(prevState => ({
  ninjas: [...prevState.ninjas, newNinja]
}));

or even:

this.setState(({ninjas}) => ({
  ninjas: [...ninjas, newNinja]
}));

It's due to state changes are asynchronous and could be batched due to performance reasons.

If you change the state using some variable which is not based on any value from state - you're free to use a simple version:

this.setState({
  answer: 42
});

Regarding your

since we use a new array each time in the first example

indeed you create a new array each time, but you create it using some set of items which can be not relevant by that time when actual state change will be performed by React under the hood.

Setting states with array helped me in pagination cases works without loosing any data from states

this.setState(prevState => ({
          ninjas: [...prevState.ninjas, ...newNinja]
}));

As you are beginner so i would like to explain you a bit.

in the code below

...this.state.ninjas

these ... is called spread syntax, soo what following code snipet do is to concate the existing state with the new items; what it results in is to re-render the component with updated state.

const updatedNinjas = [...this.state.ninjas, newNinja];

    this.setState({
      ninjas: updatedNinjas
    });
As for as comparision is concerend they both do the same thing, what react documentation suggests is that first approach may fail but it doesn't say it always fail as i have never seen it failing in my 1.5 years of react experience.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!