这是我的仓库https://github.com/extrapractice/lambda-calculator/tree/revised
发生了什么事,当我为useState使用React钩子时,它工作正常,但是,我在useEffect上设置了事件监听器,用于何时按下键(它是计算器),但是由于某种原因,按下键并触发事件,反应状态未定义?
为什么会这样,我该如何纠正?
const Calculator = (props) => {
const [ display, setDisplay ] = useState('');
useEffect(() => {
window.addEventListener('keydown', handlekeyDown);
// window.addEventListener('keydown', handleEquals);
return () => {
window.addEventListener('keydown', handlekeyDown);
// window.addEventListener('keydown', handleEquals);
};
}, []);
function handlekeyDown(e) {
e.preventDefault();
const current = e.key;
const values = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', '*', '/'];
if (values.includes(current)) {
let value = current;
setDisplay((prev) => prev + value);
}
}
function handleEquals(e) {
const value = e.key
console.log(display)
if (value === '=') {
const solution = math.evaluate(display)
const histEntry = { problem: display, solution: solution };
props.setHistory((prev) => [ ...prev, histEntry ]);
setDisplay(solution);
}
}
function addToString(e) {
console.log(e.target)
let value = e.target.value;
if (value === '=') {
const histEntry = { problem: display, solution: math.evaluate(display) };
props.setHistory((prev) => [ ...prev, histEntry ]);
setDisplay(math.evaluate(display));
} else {
setDisplay((prev) => prev + value);
}
}
答案 0 :(得分:0)
那么解决此问题的方法是将handleKeydown添加到useEffect的依赖项数组中。之所以这样,是因为我没有缩小100%的确切原因,但是我有一个很明确的想法。