[英]React Hotkeys cannot access updated state
I am using GlobalHotKeys<\/code> provided by
react-hotkeys<\/code> library to trigger some event when specified keyboard shortcut is entered.
我正在使用
react-hotkeys<\/code>库提供的
GlobalHotKeys<\/code>在输入指定的键盘快捷键时触发某些事件。
But the handler function cannot get the updated value of the state.
但是处理函数无法获取状态的更新值。 Following is the code I used.
以下是我使用的代码。
code sandbox code is available here: this link<\/a>代码沙箱代码可在此处获得:
此链接<\/a>
import React from 'react'
import { GlobalHotKeys } from 'react-hotkeys'
function Playground() {
const [count, setCount] = React.useState(0)
const handleEvent = React.useCallback(() => {
console.log("Count Value now is: ", count)
}, [])
return (
<GlobalHotKeys
keyMap={{
FOCUS_BARCODE: 'alt+a'
}}
handlers={{
FOCUS_BARCODE: handleEvent
}}>
<div>
<h1>Here is count value: {count}</h1>
<button onClick={() => setCount((count) => count + 1)}> Increase Count</button>
</div>
</GlobalHotKeys>
)
}
export default Playground
I've updated your code example to work with the hotkey.我已经更新了您的代码示例以使用热键。 You have to put your console log in a useEffect call as it is a side-effect.
您必须将控制台日志放入 useEffect 调用中,因为它是一种副作用。
import React, { useEffect } from "react";
import { GlobalHotKeys } from "react-hotkeys";
function Playground() {
const [count, setCount] = React.useState(0);
const handleEvent = React.useCallback(() => {
setCount((count) => count + 1);
}, [setCount]);
useEffect(() => {
console.log("Count Value now is: ", count);
}, [count]);
return (
<GlobalHotKeys
keyMap={{
FOCUS_BARCODE: "alt+a"
}}
handlers={{
FOCUS_BARCODE: handleEvent
}}
>
<div>
<h1>Here is count value: {count}</h1>
<button onClick={() => setCount((count) => count + 1)}>
{" "}
Increase Count
</button>
</div>
</GlobalHotKeys>
);
}
export default Playground;
Sandbox - https://codesandbox.io/s/laughing-newton-08vyv沙盒 - https://codesandbox.io/s/laughing-newton-08vyv
useEffect - https://reactjs.org/docs/hooks-effect.html useEffect - https://reactjs.org/docs/hooks-effect.html
You have to add allowchanges..你必须添加allowchanges ..
<GlobalHotKeys
keyMap={{
FOCUS_BARCODE: 'alt+a'
}}
handlers={{
FOCUS_BARCODE: handleEvent
}}
allowChanges={true}
>
<div>
<h1>Here is count value: {count}</h1>
<button onClick={() => setCount((count) => count + 1)}> Increase Count</button>
</div>
</GlobalHotKeys>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.