我正在使用React创建一个Hangman游戏。我创建了一个函数(onGuess),用于检查猜测是否为badGuess,是否为唯一猜测,然后进行猜测(makeGuess)。为此,我引用了guessAlreadyGiven和LettersOnPhrase(两个数组)。但是,我发现调用onGuess时,两个数组在调用makeGuess之前都是空的。
在调用makeGuess之前如何确保两个数组都被调用?
我尝试过移动代码,但无济于事。
import React, { useContext, useEffect, Fragment } from 'react'
import Letter from './Letter'
import puzzleContext from '../../context/puzzle/puzzleContext'
let alphabet
const Letters = () => {
const {
makeGuess,
guessesAlreadyGiven ,
decrementGuesses,
LettersOnPhrase
} = useContext(puzzleContext)
alphabet = //an array of letters
let guess
useEffect(() => {
window.addEventListener('keypress', e => {
guess = String.fromCharCode(e.charCode).toUpperCase()
{
alphabet.includes(guess) && onGuess()
}
})
}, [guessesAlreadyGiven , LettersOnPhrase ])
const onGuess = async () => {
const unique = !guessesAlreadyGiven.includes(guess)
const isBadGuess = !LettersOnPhrase.includes(guess)
if (unique) {
makeGuess(guess)
}
if (isBadGuess) {
decrementGuesses()
}
}
return (
<Fragment>
//show a list of letter
</Fragment>
)
}
export default Letters