reactjs 设置状态不会立即更新以下React组件中的状态[duplicate]

flseospp  于 2022-11-29  发布在  React
关注(0)|答案(1)|浏览(225)

此问题在此处已有答案

The useState set method is not reflecting a change immediately(16个答案)
56分钟前关门了。
我正在React组件中侦听keypress

import * as React from "react";
import { render } from "react-dom";

function App() {
  const [keys, setKeys] = React.useState<string[]>([]);

  React.useEffect(() => {
    const handleKeypress = (event: any) => {
      if (event.key !== "]" && event.key !== "[" && event.key !== "Enter") {
        setKeys([...keys, event.key]);
        console.log(keys)
        // if you pressed, say, `d`, this should log `['d']`,
        // but it logs `[]` instead. 
      }

      // do something with keys
    };

    document.addEventListener("keypress", handleKeypress);

    return () => {
      document.removeEventListener("keypress", handleKeypress);
    };
  }, [keys]);

  return (
    <div>
      {keys.map((key: string, idx) => (
        <li key={idx}>{key}</li>
      ))}
    </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

奇怪的事情发生了。console.log(keys)会在您第一次按下某个键时记录一个空数组...但该键会显示在JSX中。
为什么会这样?如何更改代码,使console.log(keys)在您第一次按下某个键时不会记录一个空数组?我想在keys更改后立即使用它。
实时代码:https://codesandbox.io/s/changing-props-on-react-root-component-forked-bjqsxe?file=/src/index.tsx

nhaq1z21

nhaq1z211#

默认情况下,useState只做一件事,它设置新的状态并导致对函数的重新呈现。
它本质上是异步的,因此默认情况下,在它之后运行的方法通常运行
当你调用setKeys时,你触发了你的组件的重新呈现,它将再次调用这个函数。但是,函数中的console.log(keys)仍然引用useState返回的第一个值,这是你的原始值(或者最后一个值)。
如果要打印,可以使用useEffect之外的console.log

相关问题