【问题标题】:React tic-tac-toe tutorial enhancement for two loops两个循环的 React tic-tac-toe 教程增强
【发布时间】:2019-08-07 22:01:25
【问题描述】:

我被井字游戏教程增强所困扰,想知道为什么下面的代码使用 renderBoard() 函数会崩溃。另外,我在浏览器中使用 codepen,运行时堆栈转储似乎没有提供任何有用的信息,除了问题发生的位置 - 任何建议表示赞赏。

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  renderRow(row) {
    return (
      <div className="board-row">
        {this.renderSquare(row * 3 + 0)}
        {this.renderSquare(row * 3 + 1)}
        {this.renderSquare(row * 3 + 2)}
      </div>
    );
  }

  renderBoard() {
    const rows = [];
    for (row=0; row<3; row++)
      {
        rows.push(this.renderRow(row));
      }
    return ({rows});
  }

  render() {
    return (
      <div>
        {this.renderBoard()}
      </div>
    );
  }
}

【问题讨论】:

  • 需要更多信息。你怎么称呼这个?不妨给我们看看codepen。
  • 好的 - 正在解决这个问题......我是 codepen 的新手,并试图弄清楚如何让它“保存”正确版本的代码......以及如何解决 codepen 的问题当我进行代码更改时停止更新......非常令人沮丧。
  • 我更喜欢用 Stackblitz 来做 React fiddles,但不管用 :-)
  • 这里有一个指向 codepen 的链接...codepen.io/cleeharris/pen/gVBpyb 请参阅 JSX 的第 58-61 行。谢谢!

标签: reactjs render


【解决方案1】:

该代码有一些问题。

  renderBoard() {
    const rows = [];
    for (row=0; row<3; row++) // <--- (1) You haven't declared `row`. Put the word `let` in front to declare it
      {
        rows.push(this.renderRow(row));
      }
    return ({rows}); // <--- (2) You're returning an object with 1 property called rows. You should just be returning the array as-is.
  }

还有(3)渲染数组的时候,还要加上key

  renderRow(row) {
    return (
      <div key={row} className="board-row">
        {this.renderSquare(row * 3 + 0)}
        {this.renderSquare(row * 3 + 1)}
        {this.renderSquare(row * 3 + 2)}
      </div>
    );
  }

这是一个固定版本:https://codepen.io/mnpenner/pen/dxgzop

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2020-09-26
    • 2018-04-28
    相关资源
    最近更新 更多