gpt4 book ai didi

javascript - 使用react从数组中删除元素

转载 作者:行者123 更新时间:2023-12-03 01:17:03 25 4
gpt4 key购买 nike

我的任务是使用 React 构建一个 tic tac toe 游戏。我需要实现的事情之一是能够撤消之前的 Action 。我正在寻求一些帮助,以根据选择从数组中删除单个元素。我有一个 if/else if 语句,用于检查所选框是否具有 X 或 O 值。如果是,我需要从板上删除该值。

    class GameBoard extends Component {

constructor(props) {
super(props);
this.state = {
box: Array(9).fill(''),
isNext: true
};
}

handleClick(i) {
debugger
const box = this.state.box.slice();

if (box[i].includes('X') || box[i].includes('O')) {

} else if (box[i].includes('')) {
box[i] = this.state.isNext ? 'X' : 'O';
this.setState({ box: box, isNext: !this.state.isNext });
}
}

renderSquare(i) {
return <Selection value={this.state.box[i]} onClick={() => this.handleClick(i)} />
}

render() {

const winner = calculateWinner(this.state.box);
let status;
if (winner) {
status = 'Winner: ' + winner;
} else if (winner && winner === 'Draw') {
status = winner;
}
else {
status = 'Next Player: ' + (this.state.isNext ? 'X' : 'O');
}

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>
);
}
}

function calculateWinner(box) {
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 (box[a] && box[a] === box[b] && box[a] === box[c]) {
return box[a];
}
else if (!box.includes('')) {
return 'Draw';
}
}
return null;
}

export default GameBoard;

最佳答案

您可以使用索引i来更新框数组中相应的项目值来实现此目的:

handleClick(i) {
debugger
const box = this.state.box.slice();

if (box[i].includes('X') || box[i].includes('O')) {

box[i] = '' // Reset the value of box item at i in box array
this.setState({ box: box, isNext: !this.state.isNext }); // Trigger re-render

} else if (box[i].includes('')) {
box[i] = this.state.isNext ? 'X' : 'O';
this.setState({ box: box, isNext: !this.state.isNext });
}
}

关于javascript - 使用react从数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51957482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com