![](/img/trans.png)
[英]I'm trying to make sense of the React TicTacToe tutorial. How does their calculateWinner helper function operate?
[英]Can't print String from function (in react tictactoe tutorial)
我正在尝试在完成 tictactoe react 教程后实现第一个改进: Display the location for each move in the format (col, row) in the move history list.
但是我的(col,row)
's 尽管计算正确,但没有打印在按钮中。 我的按钮获得类似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);
}
});
}
这是一个使用 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);
}, '');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.