在遵循基本反应教程的同时 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;
...
答案 0 :(得分:1)
问题出在初始化状态的构造函数中。
替换
var state = {
history: [
{
squares: Array(9).fill(null)
}
],
xIsNext: true
};
与
this.state = {
history: [
{
squares: Array(9).fill(null)
}
],
xIsNext: true
};