我很难理解这是为什么:
addItem = item => {
this.setState({ grudges: [grudge, ...this.state.grudges] });
}
存在相当笨拙的实现。不会
this.state.grudges.push(grudge)
够了吗?
最佳答案
这还不够,因为 React state is expected to be immutable :
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
这个“笨拙的实现”也是不正确的,this.state
不应与 this.setState
一起使用,因为 setState
is asynchronous并可能导致竞争条件:
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
<...>
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.
正确的方法是使用updater函数:
addItem = item => {
this.setState(({ grudges }) => ({ grudges: [grudge, ...grudges] }));
}
它还受益于解构语法。
关于javascript - 添加功能的笨拙实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53685630/