問題描述
使用 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 Ricky、Codebling、YATIN GUPTA)
參考文件