反应未初始化状态

时间:2021-04-27 03:40:34

标签: javascript reactjs

在遵循基本反应教程的同时 https://reactjs.org/tutorial/tutorial.html,

我遇到了错误 TypeError: Cannot read property 'history' of null

经过一些调试后,将错误本地化为其他方法无法访问 state

在 index.js 中

constructor(props) {
        super(props);
        var state = {
            history: [
                {
                    squares: Array(9).fill(null)
                }
            ],
            xIsNext: true
        };
    }
    ...
    render() {
        const history = this.state.history; //Error thrown here
        const current = history[history.length - 1];
        const winner = this.calculateWinner(current.squares);
        let status;
        ...

1 个答案:

答案 0 :(得分:1)

问题出在初始化状态的构造函数中。

替换

        var state = {
            history: [
                {
                    squares: Array(9).fill(null)
                }
            ],
            xIsNext: true
        };

        this.state = {
            history: [
                {
                    squares: Array(9).fill(null)
                }
            ],
            xIsNext: true
        };