使用 useState 時,Reactjs 不會立即更新分配的值 (Reactjs doesn't immediately update the assigned value when useState is used)


問題描述

使用 useState 時,Reactjs 不會立即更新分配的值 (Reactjs doesn't immediately update the assigned value when useState is used)

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>
</>
);
};
</code></pre>

我嘗試過使用承諾,但我也沒有得到解決方案。

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

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


參考解法

方法 1:

React is still Javascript, and it only updates values on the next run.

See commented code below:

  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"
  };

When you run set hooks, it marks the value as updated and triggers a new render as soon as this render is done.

You can't change the update the value of state mid‑render, as the code at the top of the render() would have run with the old value.

Directly from a the React documentation:

component schedules a UI update by calling setState() [...] Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen

方法 2:

Update your code as:

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>
    </>
  );
};

(by RickyCodeblingYATIN GUPTA)

參考文件

  1. Reactjs doesn't immediately update the assigned value when useState is used (CC BY‑SA 2.5/3.0/4.0)

#use-state #react-hooks #reactjs #asynchronous






相關問題

為什麼在使用 useState 時初始加載狀態設置為 true? (Why the initial loading state is set to true while using useState?)

如何在 React 中提取狀態的值 (How to extract value of a state in React)

如何在使用狀態掛鉤更新狀態時覆蓋具有相同鍵的對象 (How can overwrite objects that have the same key in updating State with state hooks)

如何使用 useState 將許多元素添加到數組中? (How to add many elements to an array with useState?)

如何正確附加到在功能組件中作為道具傳遞的字符串數組 (How to properly append to string array that was passed as props in functional component)

useState 在功能上與組件 React 的行為不同 (useState behaves differently in function vs componenet React)

如何在反應鉤子中設置多個值來狀態 (How to set multiple values to state in react hooks)

在 reactJS 中使用 useState 和外部過濾器 (using useState and External Filters in reactJS)

React.js 更改下拉值 (React.js to change dropdown value)

useState 不會立即更新狀態 (useState is not updating state immediately)

使用 useState 時,Reactjs 不會立即更新分配的值 (Reactjs doesn't immediately update the assigned value when useState is used)

如何為 useState 創建動態函數名稱? (How do I create a dynamic function name for useState?)







留言討論