简体   繁体   English

State 未在控制台中显示更新值

[英]State not showing updated value in console

Although the text gets updated on the page, the console.log still logs out the initial value.尽管页面上的文本得到了更新,但 console.log 仍然会注销初始值。 Why is this?为什么是这样? I know that setting the state is asynchronous but why does it still log out the old value even after waiting 1 second?我知道设置 state 是异步的,但为什么即使等待 1 秒后它仍会注销旧值?

import { useState, useEffect, useRef } from "react";

function App() {
  const [requestState, setRequestState] = useState("initial");

  useEffect(() => {
    setRequestState("changed");
    setTimeout(() => {
      console.log(requestState);
    }, 1000);
  }, []);

  return (
    <div className="App">
      {requestState}
    </div>
  );
}

export default App;

useEffect will run when the component renders,To call a function conditionally, specify the list of dependencies. useEffect 将在组件渲染时运行,要有条件地调用 function,请指定依赖项列表。 And the rule of thumb is to always add those dependencies that you are using inside the useEffect()经验法则是始终在 useEffect() 中添加您正在使用的那些依赖项

    import { useState, useEffect, useRef } from "react";
    
    function App() {
    const [requestState, setRequestState] = useState("initial");
    setRequestState("changed");  
    useEffect(() => {
    setTimeout(() => {
      console.log(requestState);
    }, 1000);
    }, [requestState]);

      return (
        <div className="App">
          {requestState}
        </div>
      );
    }
    
    export default App;

Your useEffect depends on the requestState varible, so pass it inside the empty list like so:您的useEffect取决于 requestState 变量,因此将其传递到空列表中,如下所示:

useEffect(() => {some code},[used variables])

The useEffect() hook "captures" state and props when it is executed. useEffect()钩子在执行时“捕获” state 和道具。 That is why it has a stale value.这就是为什么它具有陈旧的价值。 The value is from when the function in useEffect() was run.该值来自运行useEffect()中的 function 时的值。

This is a beautiful article by Dan Abramov: https://overreacted.io/a-complete-guide-to-useeffect/ .这是 Dan Abramov 的一篇漂亮文章: https://overreacted.io/a-complete-guide-to-useeffect/ It has an explanation about almost the exact same problem as yours.它对与您的问题几乎完全相同的问题进行了解释。 Read it completely to have a great insight into useEffect()完整阅读它以深入了解useEffect()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM