我正在制作一个连接四子游戏。每一列(组件)从父组件获得当前玩家的颜色作为属性。我在每个列中有一个回调函数,每次点击列时更改当前玩家状态,但由于某种原因,这些列不接受新的父状态作为更新后的属性。
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生命周期钩子创建的?如果是这样,我该如何修复它而不需要太多修改代码结构?