【发布时间】: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