![](/img/trans.png)
[英]Replacing underscores with letters of corresponding word in Hangman game in Javascript
[英]Reveal left over underscores one at a time at end of Hangman TypeScript game
游戲結束后,我嘗試使用 setTimeout 將下划線替換為他們一次錯過的字母。 此函數將下划線與正確的字母交換,但是在接下來的渲染中將字母放回下划線並重復此過程,直到只顯示最后一個丟失的字母為止。 我需要所有字母來完全換出 state.underscores,它是一個字符串數組。
state.missingIndex 是一個數字數組; 缺少字母索引
word 是玩家猜測的完整單詞
使用 useReducer 鈎子改變狀態
反應鈎子和打字稿
const displayMissingLetters = () => {
let wrongWord: string[] = [];
state.losses.missingIndex.forEach((num, index) => {
setTimeout(() => {
wrongWord = state.underscores
.map((alpha: string, i: number) =>
alpha === "_" && word[i] === word[num] ? word[num] : alpha
);
dispatch({ type: "SET_UNDERSCORES", underscores: wrongWord });
}, index * 300);
});
}
這是它現在的樣子:
這是 wrongWord 在控制台中的樣子:
問題是當超時函數觸發時,它有一個陳舊的狀態副本,在所有超時第一次安排時設置。
看起來您在這里使用了減速器,所以最簡單的方法是在減速器中處理它。 Reducers 在開始運行時獲得當前狀態,因此它們不應該有舊的/過時的狀態。
setTimeout(() => {
dispatch({ type: "REVEAL_LETTER", index: num });
}, index * 300)
然后將用字母替換下划線的邏輯移動到reducer,並將其保存回狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.