【发布时间】:2021-04-05 14:08:45
【问题描述】:
我做了一个井字游戏(react 自己的文档),现在我正在尝试更改一些功能,在这种情况下,我更改的第一件事是用户可以在游戏完成后观察之前的动作超过。我已经想出了我正在寻找的结果,但是我必须再单击一次才能使获胜者值发生变化,因此,要使底部按钮出现(让您浏览游戏历史的按钮移动通过移动)。你知道是什么原因造成的吗?我该如何解决?
这是我的代码: (我尝试了几种解决方案,但都没有奏效,我不知道是什么原因导致了这个问题,这就是我放整个代码的原因)
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
class Board extends React.Component {
renderSquare(i) {
return <Square value={this.props.squares[i]}
onClick={()=>{this.props.onClick(i)}}/>;
}
render() {
return (
<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>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props)
this.state = {
history: [{
squares: Array(9).fill(null)
}],
stepNumber: 0,
xIsNext: true,
winner: null
}
};
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares: squares,
}]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
});
}
checkForWinner(squares,winr) {
if (winr === null)
this.setState({
winner: calculateWinner(squares)
})
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = this.state.winner
const moves = history.map((_, move) => {
const desc = move ?
'Go to move #' + move :
'Go to game start';
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={i => {
if (!winner) {
this.handleClick(i)
}
this.checkForWinner(current.squares, winner)
}}
/>
</div>
<div className="game-info">
<div>{(winner) ? 'Winner: ' + winner : 'Next player: ' + (this.state.xIsNext ? 'X' : 'O')}</div>
<ol>{(winner) ? moves : null}</ol>
</div>
</div>
);
}
}
ReactDOM.render(
<Game />,
document.getElementById('root')
);
【问题讨论】:
标签: javascript reactjs