Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - 在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?(我想在state数组的末尾添加一个元素,这是正确的方法吗?)

this.state.arrayvar.push(newelement);
this.setState({arrayvar:this.state.arrayvar});

I am concerned that modifying the array in-place with push might cause trouble - is it safe?(我担心通过push就地修改数组可能会引起麻烦-是否安全?)

The alternative of making a copy of the array, and setState ing that seems wasteful.(复制数组和setState替代方法似乎很浪费。)

  ask by fadedbee translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The React docs says:(React文档说:)

Treat this.state as if it were immutable.(将this.state视为不可变的。)

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.(您的push将直接改变状态,即使您此后再次“重置”状态,也有可能导致易于出错的代码。)

F.ex, it could lead to that some lifecycle methods like componentDidUpdate won't trigger.(例如,它可能导致某些生命周期方法(例如componentDidUpdate不会触发。)

The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:(在更高版本的React中,建议的方法是在修改状态以防止竞争情况时使用updater函数:)

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.(与使用非标准状态修改可能会遇到的错误相比,内存“浪费”不是问题。)

Alternative syntax for earlier React versions(早期React版本的替代语法)

You can use concat to get a clean syntax since it returns a new array:(您可以使用concat获得干净的语法,因为它返回一个新数组:)

this.setState({ 
  arrayvar: this.state.arrayvar.concat([newelement])
})

In ES6 you can use the Spread Operator :(在ES6中,您可以使用Spread运算符 :)

this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...