[英]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.