[英]Global variable is undefined inside a const function React
When I try to get current value of a variable outside a const function in React then it would not an issue, while getting access to a variable INSIDE a const function it gives me an error.当我尝试在 React 中获取 const function 之外的变量的当前值时,这不会成为问题,而在访问 const function 内部的变量时,它会给我一个错误。
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> )
In vanilla this.isGuessed should be working properly but in React this is not the case.在原版中 this.isGuessed 应该可以正常工作,但在 React 中并非如此。
useEffect(() => { checkLetters(isGuessed); }, [isGuessed]);
It's because of yout useCallback
you need to pass a second parameter for the "cache" version to update.这是因为您需要使用useCallback
传递第二个参数以更新“缓存”版本。
const handleKeyPress = useCallback(event => {
// logic here
}, [isGuessed]);
Pass the is guessed so handleKeyPress
will re update the resulting value if isGuessed
change.传递 isguessed ,因此如果isGuessed
更改, handleKeyPress
将重新更新结果值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.