定義我有一個函數currentPlayer
如下:本地變量沒有在功能
function currentPlayer(players) {
return players.findIndex(player => player.current) || 0;
}
我想如下使用此功能在減速:
export function players(players = [], action) {
players = players.slice();
switch (action.type) {
...
case DELETE_PLAYER:
const currentPlayer = currentPlayer(players);
if (currentPlayer === action.index) {
players = switchNextPlayer(players, currentPlayer);
}
players.splice(action.index, 1);
}
return players;
}
在運行該代碼,我收到以下錯誤:
ReferenceError: currentPlayer is not defined
如果我按如下方式更改變量名稱,代碼將起作用:
const currentPlayerIndex = currentPlayer(players);
我認爲變量currentPlayer
將在減速功能的作用域。這裏發生了什麼?
'const currentPlayer = currentPlayer(players);'注意行中的3個名字 – Ryan
該函數正在被新的'currentPlayer'綁定所掩蓋,而這個綁定在你評估它時還沒有被初始化,所以你最終得到了一個參考錯誤 – MinusFour