React - 功能setState(以前的状态)与新的更新值不同? [英] React - Functional setState (previous state) different from new updated value?

查看:283
本文介绍了React - 功能setState(以前的状态)与新的更新值不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试通过多个近期课程学习 React

I'm currently trying to learn React by multiple recent courses.

要更新州,大多数课程建议采用这种方式:

To update an state, most courses suggest going this way:

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

    this.setState({
      ninjas: updatedNinjas
    });

但是,因为 setState 是异步 ,官方反应文件建议使用以前的状态并根据此状态进行更新。

However, since setState is "asynchronous", the official react documentation recommends to use the previous state and update based on this one.

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

两者都解决了同样的问题(因为我们在第一个例子中每次都使用一个新数组)或者只是最后一个万无一失?

Are both solving the same issue (since we use a new array each time in the first example) or is only the last one foolproof?

推荐答案

如果您的新状态是根据已经处于状态的任何值计算的 - 那么您应该使用第二种形式的 setState 你在哪里使用一个函数:

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]
}));

甚至:

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
});

关于你的


因为我们在第一个例子中每次都使用一个新数组

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

确实每次创建一个新数组,但是你创建了它使用了一些项目,当实际状态变化将由引擎盖下的 React 执行时,这些项目可能无关。

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.

这篇关于React - 功能setState(以前的状态)与新的更新值不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆