全局变量在const函数React中未定义

时间:2019-11-14 22:34:58

标签: javascript reactjs react-hooks

当我尝试在React中获取const函数之外的变量的当前值时,这不会有问题,而在const函数内部访问变量时却给了我一个错误。

const revealMatchedWord = (string, guessed) => {
    if(string.length > 0) {
        const regExpr = new RegExp(`[^${guessed.join("")}\\s]`, 'ig');
        return string.replace(regExpr, '_');
    } else {
        return;
    }
}

let curr = revealMatchedWord(guessWord, updatedArray);
let isGuessed = curr === guessWord; // check if word is guessed
console.log('isGuessed ' + isGuessed); // true

const checkLetters = () => {
    console.log('isGuessed ' + isGuessed); // undefined
}

    const handleKeyPress = useCallback(event => {
        let letter = String.fromCharCode(event.keyCode).toLowerCase();
        if(event.keyCode >= 65 && event.keyCode <= 90) {
            checkLetters();
        } else if(event.keyCode == 13) {
            event.preventDefault();
            return;
        } else {
            return;
        }
    });

    useEffect(() => {
        document.addEventListener('keydown', handleKeyPress);

        return () => {
            document.removeEventListener('keydown', handleKeyPress);
        }
    }, [handleKeyPress]);

return (
  <div>
        <p>{revealMatchedWord(guessWord, updatedArray)}</p>
  </div>
)

在香草中,isGuessed应该可以正常工作,但在React中,情况并非如此。

2 个答案:

答案 0 :(得分:0)

    useEffect(() => {
       checkLetters(isGuessed);
    }, [isGuessed]);

答案 1 :(得分:0)

由于useCallback,您需要传递第二个参数以更新“缓存”版本。


    const handleKeyPress = useCallback(event => {
        // logic here
    }, [isGuessed]);

猜测通过,因此如果handleKeyPress发生更改,isGuessed将重新更新结果值。