reactjs在状态中设置了错误的值

时间:2018-12-21 15:13:58

标签: reactjs

我是一个非常新的反应者,在以下官方教程https://reactjs.org/tutorial/tutorial.html上尝试了自己的运气。我知道了现在,我正在对其进行实验,并尝试通过两个循环生成tic tac toe字段。

当我单击单个字段时,将设置列中所有三个字段的值(仅应设置我单击的字段),并且初始历史记录条目处于状态(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;
}

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

我想念什么?
谢谢

1 个答案:

答案 0 :(得分: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]]这样的显式2D数组可能会更好。