我正在完成tictactoe react教程后尝试实现第一个改进:Display the location for each move in the format (col, row) in the move history list.

但是,尽管我的(col,row)是正确计算的,但并未在按钮中打印。我的按钮会显示Go to move #1 (undefined)之类的文本。应该打印(col,row)值,而不是未定义的值。

为什么会这样呢?

这是我的代码:

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

  const moves = history.map((step,move) => {
    const desc = move ? 'Go to move # ' + move + ' ('+getRowCol(history, move)+ ')': 'Go to game start';
    return (
      <li key={move}><button onClick={() => this.jumpTo(move)}>{desc}</button></li>
    )
  });

 (...)

 function getRowCol(history, move){
  let array1 = history[move].squares;
  let array2 = history[move-1].squares;
  array1.forEach((item,index) => {
   if(item !== array2[index]){
    return nomearIndice(index);
   }
  });
 }
 function nomearIndice(indice){
  let retorno = indice < 3 ? '1,' : indice < 6 ? '2,' : '3,';
  if([0,3,6].includes(indice)){
   return retorno + '1';
  } if([1,4,7].includes(indice)){
   return retorno + '2';
  } if([2,5,8].includes(indice)){
   return retorno + '3';
  }
 }


因此,我在代码示例的第6行中运行history.map,此方法调用getRowCol函数,据我所知,通过在代码中放入一百万个console.log可以正常工作。我猜JS不会等到我的getRowCol函数返回并产生这种不良结果。有问题吗?如果是这样,我该如何解决?

提前致谢

最佳答案

看起来您没有从getRowCol返回任何内容
尝试


function getRowCol(history, move) {
  let array1 = history[move].squares;
  let array2 = history[move - 1].squares;
  return array1.map((item, index) => {
    if (item !== array2[index]) {
      return nomearIndice(index);
    }
  });
}




Here是使用map并返回结果的演示。但是,我不确定您期望什么输出。

您能解释一下您要从getRowCol获得的结果(例如示例)吗,我可以尝试提供帮助。

我已经更新了演示以反映您使用后的行为

function getRowCol(history, move) {
  let array1 = history[move].squares;
  let array2 = history[move - 1].squares;

  return array1.reduce((accumulator, item, index) => {
    return (item === array2[index]) ? accumulator : nomearIndice(index);
  }, '');
}

09-25 16:13