使用react从数组中删除元素

时间:2018-08-21 22:21:33

标签: javascript reactjs

我的任务是使用react构建井字游戏。我需要实现的一件事是撤消先前动作的能力。我正在寻找有关基于选择从数组中删除单个元素的帮助。我有一个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;

1 个答案:

答案 0 :(得分:1)

您可以使用索引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 });
  }
}