Reactjs React Tic Tac Toe,Array.slice(),易变性

Reactjs React Tic Tac Toe,Array.slice(),易变性,reactjs,Reactjs,在react-tic-tac-toe中,为什么他们必须使用Array.slice() 他们改变了状态。反正方格对吧?试图了解发生了什么。创建新数组并将所有元素复制到其中是一种常见的方法。这是为了将new数组传递给setState,而不是对旧数组进行变异-这不会导致组件重新渲染 新数组将导致重新渲染。如果您对数组进行了如下变异: this.props.squares[i] = 'X'; react不会被通知状态发生了更改。您不应该直接改变状态,因此当您编写 handleClick(i) { c

在react-tic-tac-toe中,为什么他们必须使用Array.slice()


他们改变了状态。反正方格对吧?试图了解发生了什么。

创建新数组并将所有元素复制到其中是一种常见的方法。这是为了将new数组传递给
setState
,而不是对旧数组进行变异-这不会导致组件重新渲染

新数组将导致重新渲染。如果您对数组进行了如下变异:

this.props.squares[i] = 'X';

react不会被通知状态发生了更改。

您不应该直接改变状态,因此当您编写

handleClick(i) {
 const squares = this.state.squares.slice(); // you are creating a new copy of the squared array,
 squares[i] = 'X';
 this.setState({squares: squares});
}
对克隆状态所做的任何更改都不会反映在原始状态上

当您希望使用生命周期方法并比较prevState和currentState时(例如,如果您将状态设置为

handleClick(i) {
 const squares = this.state.squares;
 squares[i] = 'X';
 this.setState({squares: squares});
}
在本例中,比如说,在
componentdiddupdate
函数中,您希望根据方格数组中的更改采取一项操作

componentDidUpdate(prevProps, prevState) {
   if(nextState.squares !== this.state.squares) {
      // do something here
   }
}
在上述情况下,比较将失败,因为
prevState
this.state
将返回与原始状态相同的结果


调用
setState
也有必要重新渲染

不会用新数组重新渲染重置状态?太好了。谢谢
componentDidUpdate(prevProps, prevState) {
   if(nextState.squares !== this.state.squares) {
      // do something here
   }
}