1
我一直在关注官方React Tutorial here。而且我已经达到了点击一个方块的程度,它调用了Board的handleClick函数来更新方块状态。
但是,在Board类中更新状态之后,它们不会传播到广场的状态。
这里是我的代码:将状态传递给子组件 - 反应教程
class Square extends React.Component {
constructor() {
super();
this.state = {
value: null,
};
}
render() {
return (
<button className="square" onClick={() =>this.props.onClick()} >
{this.state.value}
</button>
);
}
}
class Board extends React.Component {
constructor() {
super();
this.state = {
squares: Array(9).fill(null),
};
}
renderSquare(i) {
return <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} />;
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = 'X';
debugger;
this.setState({squares: squares});
}
}
https://codepen.io/mohamed3on/pen/jVVyWZ?editors=1010 我跟着教程完全相同,直到“为什么不变性很重要”的一部分。我知道
我同意,除了部分“作为一般指导原则,建议避免一直使用状态”。我看不出有什么好的理由阻止整个国家的使用。请参阅[gaeron关于此事的建议](https://github.com/reactjs/redux/issues/1287#issuecomment-175351978)(与Redux相关,但也适用于任何其他州管理库)。 – ArneHugo
同意。这就是我试图通过说*避免*和*准则*而不是永远甚至敢于使用或面对即时惩罚的方式来传达永恒痛苦的灵魂所造成的-疼痛。在你分享的链接中,这绝对是更好的解释。谢谢。 – Leandro