首页 > 解决方案 > React 热键无法访问更新状态

问题描述

当输入指定的键盘快捷键时,我正在使用库GlobalHotKeys提供的react-hotkeys来触发某些事件。但是处理函数无法获取状态的更新值。以下是我使用的代码。

代码沙箱代码可在此处获得:此链接


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

现在发生了什么

任何时候我点击alt+a,它的控制台日志都算作0. 我点击了Increase count按钮并增加了 的值,count然后点击alt+a仍然给出了countto的值0

我需要的

我想count用热键打印更新后的值。

标签: javascriptreactjsreact-hookshotkeys

解决方案


你必须添加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>

推荐阅读