【问题标题】:reactjs sets wrong values in statereactjs 在状态中设置了错误的值
【发布时间】:2018-12-21 15:13:58
【问题描述】:

我对这个官方教程很陌生,并尝试了我的运气:https://reactjs.org/tutorial/tutorial.html。我让它工作了。现在我正在对其进行试验,并尝试生成带有两个循环的井字游戏。

当我点击一个字段时,该列中所有三个字段的值都被设置(只有我点击的那个应该被设置)和状态中的初始历史条目(state.history[0].squares所有字段 'null') 都被覆盖,这不应该发生。

function Square(props) {
    return (
        <button className="square" onClick={props.onClick}>
           {props.value}
        </button>
    );
}

function Board(props) {
    const rows = [];
    for(let i=0; i<3; i++) {
        const cols = [];
        for(let j=0; j<3; j++) {
            cols.push(
                <Square
                    key={i + "_" + j}
                    value={props.squares[i][j]}
                    onClick={() => props.onClick(i, j)}
                />
            );
        }
        rows.push(
            <div key={i} className="board-row">
                {cols}
            </div>
        );
    }
    return (<div>{rows}</div>);
}

class Game extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            history: [{
                squares: Array(3).fill(Array(3).fill(null)),
                field: '/'
            }],
            stepNumber: 0,
            xIsNext: true,
        };
    }

    handleClick(i, j) {
        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][j]) {
            return;
        }
        squares[i][j] = this.getNexPlayer();
        this.setState({
            history: history.concat([{
                squares: squares,
                field: '(' + (j+1) + ',' + (i+1) + ')',
            }]),
            stepNumber: history.length,
            xIsNext: !this.state.xIsNext,
        });
    }

    jumpTo(step) {
        console.log(this.state);
        this.setState({
            stepNumber: step,
            xIsNext: (step % 2) === 0,
        });
    }

    getNexPlayer() {
        return this.state.xIsNext ? 'X' : 'O';
    }

    render() {
        const history = this.state.history;
        const moves = history.map((step, move) => {
            const desc = move ? 'Go to move #' + move + ' ' + step.field : 'Go to game start';
            return (
                <li key={move}>
                    <button
                        className={this.state.stepNumber === move ? 'bold' : ''}
                        onClick={() => this.jumpTo(move)}
                    >
                        {desc}
                    </button>
                </li>
            );
        });
        const current = history[this.state.stepNumber];
        let status = 'Next player: ' + this.getNexPlayer();
        const winner = calculateWinner(current.squares);
        if(winner) {
            status = 'Winner: ' + winner;
        } else if(history.length === 10) {
            status = 'DRAW';
        }

        return (
            <div className="game">
                <div className="game-board">
                    <Board
                        squares={current.squares}
                        onClick={(i, j) => this.handleClick(i, j)}
                    />
                </div>
                <div className="game-info">
                    <div>{status}</div>
                    <ol>{moves}</ol>
                </div>
            </div>
        );
    }
}

// ========================================

ReactDOM.render(
    <Game />,
    document.getElementById('root')
);

function calculateWinner(squares) {
    const solutions = [
        [[0,0], [0,1], [0,2]],
        [[1,0], [1,1], [1,3]],
        [[2,0], [2,1], [2,3]],
        [[0,0], [1,0], [2,0]],
        [[0,1], [1,1], [2,1]],
        [[0,2], [1,2], [2,2]],
        [[0,0], [1,1], [2,2]],
        [[2,0], [1,1], [0,2]],
    ];
    for(let i = 0; i < solutions.length; i++) {
        const [a, b, c] = solutions[i];
        if(squares[a[0]][a[1]] && squares[a[0]][a[1]] === squares[b[0]][b[1]] && squares[a[0]][a[1]] === squares[c[0]][c[1]]) {
            return squares[a[0]][a[1]];
        }
    }
    return null;
}

想法是建立一个井字游戏,保存历史中的所有动作,您可以在历史中的动作之间切换。

我错过了什么?
谢谢

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    数组是可变的,因此对 1 个数组的 3 个引用都指向同一个数组 - 问题中的代码 squares: Array(3).fill(Array(3).fill(null)) 类似于:

    const a = [null, null, null]
    const b = [a, a, a]
    b[0][0] = 1
    console.log(a) // [1, null, null]
    

    使用像 [[0,0,0], [0,0,0], [0,0,0]] 这样的显式二维数组可能会更好

    【讨论】:

    • 虽然我认为OP需要深拷贝多维数组:const squares = current.squares.map((square) =&gt; square.slice())
    • 我明白了。因此,这两个问题都是由数组引用引起的,但却是独立的问题。它现在正在工作。谢谢你们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2016-12-09
    • 2014-09-23
    • 2021-10-17
    • 2020-04-17
    • 2019-04-04
    • 1970-01-01
    相关资源
    最近更新 更多