javascript - React 教程给出 TypeError

标签 javascript reactjs

我决定学习React并从官方教程开始。在我达到代码的这种状态之前一切都很好。问题似乎与游戏组件的渲染函数中的电流属性平方有关,该函数已定义,但我不确定为什么它被标记为错误

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

class Board extends React.Component {
  renderSquare(i) {
    return <Square value = {this.props.squares[i]} onClick = {() => this.props.onClick(i)} />;
  }
  render() {
    return (
      <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>
    );
  }
}

class Game extends React.Component {
  constructor() {
    super();
    this.state = {
      history : [{
        squares : Array(9).fill(null)  
      }],
      xIsNext : true
    };
  }
  handleClick(i){
    const history = this.state.history.slice(0, this.state.stepNumber);
    const current = history[this.state.stepNumber];
    const squares = current.squares.slice();
    if(calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history : history.concat([{
        squares : squares
      }]),
      xIsNext : !this.state.xIsNext,
      stepNumber : 0,
    });
  }
  jumpTo(step){
    this.setState({
      stepNumber : step,
      xIsNext : (step % 2) ? false : true,
    });
  }
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    let status;
    if(winner) {
      status = 'Winner : ' + winner;
    }
    else {
      status = 'Next Player : ' + (this.state.xIsNext ? 'X' : 'O');
    }
    const moves = history.map((step, move) => {
      const desc = move ? 'Move #' + move : 'Game start';
      return (
        <li key = {move}>
          <a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
        </li>
      );
    });

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

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

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

function calculateWinner(squares) {
  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 (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

这是我得到的错误

TypeError: Cannot read property 'squares' of undefined
    at Game.render (pen.js:208:41)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:6336:34)
    at ReactCompositeComponentWrapper._renderValidatedComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:6356:32)
    at ReactCompositeComponentWrapper.wrapper [as _renderValidatedComponent] (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:12879:21)
    at ReactCompositeComponentWrapper.mountComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:5969:30)
    at ReactCompositeComponentWrapper.wrapper [as mountComponent] (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:12879:21)
    at Object.mountComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:13613:35)
    at ReactCompositeComponentWrapper.mountComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:5974:34)
    at ReactCompositeComponentWrapper.wrapper [as mountComponent] (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:12879:21)
    at Object.mountComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:13613:35)

最佳答案

因此,在您的游戏渲染函数中,您从这三行代码开始

const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);

但是,在您的 Game 构造函数中,您没有在状态中设置 stepNumber:

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

因此,当你这样做

const current = History[this.state.stepNumber]

你本质上做的是

const current = 历史[未定义]

这意味着当你这样做时

const Winner =calculateWinner(current.squares)

你实际上在做

const Winner =calculateWinner(undefined.squares)

这就是你的问题。您需要在构造函数中设置您的状态的stepNumber。

关于javascript - React 教程给出 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41142123/

相关文章:

reactjs - ESLint React-Router v4 - 如何验证匹配参数 Prop ?

javascript - 在 javascript 中使用特定键反转对象数组时出现问题(React)

css - 我想让它成为一个带有链接标签的点击元素,但我有 css 问题

javascript - 来自 JSON D3.JS 的分组条形图

javascript - 当数据是js对象时,用d3重新定位传单上的点

javascript - 如何避免在 asp.net 中的每个服务器端事件刷新页面?

javascript - 如何使 2 个 Javascript 变量始终彼此相等?

javascript - JS "upgrade"模式

javascript - Redux-Saga 文档中奇怪的登录流程示例

javascript - 防止将重复对象添加到状态 react redux