React热键无法访问更新状态

问题描述

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

代码沙箱代码可在此处获得:this link


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仍将count的值设为0

我需要的

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

解决方法

我已经更新了您的代码示例以使用热键。您必须将控制台日志放入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;

沙箱-https://codesandbox.io/s/laughing-newton-08vyv

useEffect-https://reactjs.org/docs/hooks-effect.html