我需要我的反应组件在用户按下键(keyUp(时执行一个函数,但我有下一个错误:
react-dom.development.js:55 Uncaught Invariant Violation: Too many re-renders.
React limits the number of renders to prevent an infinite loop.
我正在使用指向事件键盘的钩子:
function useKey(key) {
const [pressed, setPressed] = useState(false)
const match = event => key.toLowerCase() == event.key.toLowerCase()
const onDown = event => {
if (match(event)) { setPressed(true) }
}
const onUp = event => {
if (match(event)) { setPressed(false) }
}
useEffect(() => {
window.addEventListener("keydown", onDown)
window.addEventListener("keyup", onUp)
return () => {
window.removeEventListener("keydown", onDown)
window.removeEventListener("keyup", onUp)
}
}, [key])
return pressed
}
和我的组件:
function App() {
const [state, setState] = useState("state")
const key = useKey('ArrowUp')
if(key){
// TODO
setState({...state})
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{state}
</div>
);
}
代码在这里 https://codesandbox.io/s/suspicious-ellis-zrgkt
这是您的设置状态导致的问题。在useEffect钩子中移动状态更新,每当键发生变化时,请检查键是否为真,然后更新您的状态。
function App() {
const [state, setState] = useState("state")
const key = useKey('ArrowUp')
useEffect(() => {
if(key) setState({...state});
}, [key])
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{state}
</div>
);
}