【问题标题】:Reactjs doesn't immediately update the assigned value when useState is used使用 useState 时,Reactjs 不会立即更新分配的值
【发布时间】:2021-05-17 15:56:07
【问题描述】:

Reactjs 在我使用 usestate 钩子时不会更新新值:看这个例子:

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

const Dictionary = () => {
  const [name, setName] = useState("Bob");

  useEffect(() => {
    updateName();
  }, []);

  const updateName = () => {
    setName("John");
    console.log("name:", name); // prints "Bob"
    setName(myName => "John");
    console.log("name:", name); // prints "Bob"
  };

  return (
    <>
      <h2>Dictionary</h2>
    </>
  );
};

我尝试过使用 Promise,但我也没有得到解决方案。

const updateName = async () => {
    await uName("John");
    console.log(name); // "Bob"
  };

  const uName = (nam) => {
    return new Promise((res, rej) => {
      setName(nam);
      res();
    });
  };

【问题讨论】:

    标签: reactjs asynchronous react-hooks use-state


    【解决方案1】:

    React 仍然是 Javascript,它只会在下次运行时更新值。

    请参阅下面的注释代码:

      const updateName = () => {
        setName("John");        // Updates the name. Will be "John" on the next render
        console.log("name:", name); // Should print "Bob"
        setName(myName => "John");  // Will run `myName => "John"` on the next render. 
        console.log("name:", name); // Should print "Bob"
      };
    

    当您运行set 挂钩时,它会将值标记为已更新,并在此render 完成后立即触发新的渲染。

    您无法更改状态中间渲染的更新值,因为render() 顶部的代码将使用旧值运行。

    直接来自the React documentation

    组件通过调用 setState() 来安排 UI 更新 [...] 感谢 setState() 调用,React 知道状态已更改,并再次调用 render() 方法以了解屏幕上应该显示的内容

    【讨论】:

      【解决方案2】:

      将您的代码更新为:

      import React, { useState, useEffect } from "react";
      
      const Dictionary = () => {
        const [name, setName] = useState("Bob");
      
        useEffect(() => {
          updateName();
        }, []);
      
      
        useEffect(() => {
          /* Use this useEffect to perform actions when name get updated. */
          console.log(name);
        }, [name]);
      
        const updateName = () => {
          setName("John");
          console.log("name:", name); // prints "Bob"
          setName(myName => "John");
          console.log("name:", name); // prints "Bob"
        };
      
        return (
          <>
            <h2>Dictionary</h2>
          </>
        );
      };
      

      【讨论】:

      • 是的,这是我的解决方案。问题是我正在使用 setInterval 方法和音频 API 创建一个应用程序。我通常使用许多 UseEFfect() Hooks 并因此获得意大利面条代码。
      • @Ricky 为什么你不能让它运行完成并在下次运行时获取更新的值?
      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 2022-12-12
      • 2013-10-11
      相关资源
      最近更新 更多