我正在制作一款四子棋游戏。每列(组件)都会从父组件接收当前玩家颜色作为 Prop 。我在每列中都有一个回调函数,每次单击列时都会更改当前玩家状态,但由于某种原因,列不会接受新的父状态作为更新的 Prop 。
class App extends React.Component {
constructor() {
super()
this.state = {
currentPlayer: 'red',
board: null,
}
}
changePlayer = () => {
this.state.currentPlayer === 'red' ?
this.setState({
currentPlayer: 'yellow'
}) :
this.setState({
currentPlayer: 'red'
})
}
componentDidMount() {
let newBoard = [];
for(let x = 0; x < 7; x++) {
newBoard.push(<Column
key={`column ${x}`}
currentPlayer={this.state.currentPlayer}
changePlayer={this.changePlayer}
x={x}
/>)
}
this.setState({
board: newBoard,
})
}
render() {
return(
<div className="app">
<div className="board">
{this.state.board}
</div>
</div>
)
}
}
class Column extends React.Component {
constructor(props) {
super(props)
this.state = {
colors: ['white', 'white', 'white', 'white', 'white', 'white']
}
}
handleClick = () => {
for(let i = 0; i < 6; i++) {
if(this.state.colors[i] === 'white') {
let newColors = this.state.colors;
newColors[i] = this.props.currentPlayer;
this.setState({
colors: newColors
})
break;
}
}
this.props.changePlayer();
}
render() {
let column = [];
for(let y = 5; y >= 0; y--) {
column.push(<Tile
key={`${this.props.x},${y}`}
x={this.props.x}
y={y}
color={this.state.colors[y]}
/>)
}
return(
<div className="column" onClick={() => this.handleClick()}>
{column}
</div>
)
}
}
我假设问题在于列是使用 componentDidMount 生命周期 Hook 创建的?如果是这种情况,我怎样才能在不改变太多代码结构的情况下解决这个问题?
最佳答案
尚不清楚您的代码在哪里失败,但是:
// Here you are setting a reference to the array in state, not a copy
let newColors = this.state.colors;
// Here you are mutating directly the state (antipattern!)
newColors[i] = this.props.currentPlayer;
// You are setting the reference to the array that has already mutated (prevState === nextState)
this.setState({
colors: newColors
});
而是这样做:
// Make a COPY of your array instead of referencing it
let newColors = [...this.state.colors];
// Here you are mutating your CLONED array
newColors[i] = this.props.currentPlayer;
// You are setting the NEW color array in the state
this.setState({
colors: newColors
});
好的,我已经解决了您的问题。
App.js 中的更改:
for(let x = 0; x < 7; x++) {
newBoard.push(<Column
key={`column ${x}`}
// retrieve value with a method as below
currentPlayer={() => this.state.currentPlayer}
changePlayer={this.changePlayer}
x={x}
/>)
}
在 Columns.js 中:
newColors[i] = this.props.currentPlayer();
工作示例:
关于javascript - 当父组件的状态更新时,子组件的 props 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60189074/