【发布时间】:2021-02-23 20:20:49
【问题描述】:
我有以下设置:
const templates = [
'dot',
'line',
'circle',
'square',
];
const [currentTemplate, setCurrentTemplate] = useState(0);
const changeTemplate = (forward = true) => {
let index = currentTemplate;
index = forward ? index + 1 : index - 1;
if (index > templates.length - 1) {
index = 0;
} else if (index < 0) {
index = templates.length - 1;
}
setCurrentTemplate(index);
};
useEffect(() => {
console.log(`Current Template is: ${templates[currentTemplate]}`);
}, [currentTemplate]);
useKeypress('ArrowLeft', () => {
changeTemplate(false);
});
useKeypress('ArrowRight', () => {
changeTemplate(true);
});
这是useKeypress-Hook使用的:
import { useEffect } from 'react';
/**
* useKeyPress
* @param {string} key - the name of the key to respond to, compared against event.key
* @param {function} action - the action to perform on key press
*/
export default function useKeypress(key: string, action: () => void) {
useEffect(() => {
function onKeyup(e: KeyboardEvent) {
if (e.key === key) action();
}
window.addEventListener('keyup', onKeyup);
return () => window.removeEventListener('keyup', onKeyup);
}, []);
}
每当我按向左或向右箭头键时,都会触发该功能。但是currentTemplate 变量并没有改变。它始终保持在 0。useEffect 仅在我从左到右或以其他方式切换键时触发。单击同一个键两次,不会再次触发useEffect,但它应该!从右到左变化时,输出为Current Template is: square,从左到右变化时,输出为Current Template is: line。但这永远不会改变。 currentTemplate 的值始终保持为0。
我错过了什么?
【问题讨论】:
-
我认为问题可能与
useKeypress有关。您可以通过将更改功能附加到按钮来测试这一点 - 如果这有效,则意味着故障在于useKeypress-hook。你能分享一下这个钩子的实现吗? -
你完全正确!使用 to 按钮时,一切正常。我包含了我的 useKeypress-Hook,但不知道这个用例可能有什么问题......
标签: reactjs react-hooks use-state