首页 > 解决方案 > react.js tic-tac-toe - 为什么

  • 具有唯一键的不是一成不变的
  • 问题描述

    处理 react.js tic-tac-toe 教程,尝试将行、列信息添加到游戏动作列表中。我添加了一个方法来确定当前移动的行和列,这样我就可以输出类似于 Go to move #1 (row#,col#)先前移动列表中的内容。该方法返回一个字符串值,我想在<li><button>{desc}.

    但是当我在每次点击游戏板时调用该方法时,不是只更新 current <li><button>,而是使用最新信息更新所有元素。我想我可以通过在key 属性中添加 row, col 来解决这个问题,但它仍然会发生。我错过了什么?谢谢<li>row, col<li>

    代码笔: https ://codepen.io/anon/pen/qMVemJ

    render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    
    const moves = history.map((step, move) => {
      let rowCol = this.setRowCol(); // returns row, col string for step
      const desc = move ?
        'Go to move #' + move + rowCol:
        'Go to game start';
      return (
        <li key={move + rowCol}>
          <button onClick={() => this.jumpTo(move)}>{desc}
          </button>
        </li>
      );
    });
    // [...omitted code that sets the status variable...]
    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>
    );
    

    标签: reactjs

    解决方案


    一个简单的解决方案是记住在历史记录中点击了哪个方格,以及方格键。然后使用这个索引来检索点击了哪一行和哪一列。

    这是一个工作示例:https ://codepen.io/anon/pen/LJOodG?editors=0010

    setRowCol仅评估渲染按钮列表的历史的最后两个步骤,并且应该评估在该步骤时播放的内容。setRowCol应该考虑当前评估的按钮。我更新了您的代码以匹配此行为:codepen.io/anon/pen/RYjXMb?editors=0010#0


    推荐阅读