在ReactJS中正确修改状态数组 [英] Correct modification of state arrays in ReactJS
问题描述
我想在州
数组的末尾添加一个元素,这是正确的方法吗?
I want to add an element to the end of a state
array, is this the correct way to do it?
this.state.arrayvar.push(newelement);
this.setState({arrayvar:this.state.arrayvar});
我担心用 push $就地修改数组c $ c>可能会造成麻烦 - 是否安全?
I am concerned that modifying the array in-place with push
might cause trouble - is it safe?
制作数组副本的替代方法,以及 setState $ c $这似乎很浪费。
The alternative of making a copy of the array, and setState
ing that seems wasteful.
推荐答案
React docs 说:
将this.state视为它是不可变的。
Treat this.state as if it were immutable.
你的推送
将直接改变状态,这可能即使您之后再次重置状态,也可能导致容易出错的代码。 F.ex,它可能导致一些生命周期方法,如 componentDidUpdate
不会触发。
Your push
will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. F.ex, it could lead to that some lifecycle methods like componentDidUpdate
won’t trigger.
推荐的方法在以后的React版本中,在修改状态时使用更新程序函数以防止竞争条件:
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
this.setState(prevState => ({
arrayvar: [...prevState.arrayvar, newelement]
}))
与使用非标准状态修改可能遇到的错误相比,内存浪费不是问题。
The memory "waste" is not an issue compared to the errors you might face using non-standard state modifications.
早期React版本的替代语法
您可以使用 concat
来获得干净的语法它返回一个新数组:
You can use concat
to get a clean syntax since it returns a new array:
this.setState({
arrayvar: this.state.arrayvar.concat([newelement])
})
在ES6中你可以使用 Spre广告运营商:
In ES6 you can use the Spread Operator:
this.setState({
arrayvar: [...this.state.arrayvar, newelement]
})
这篇关于在ReactJS中正确修改状态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!