使用异步设置后,React hooks状态不会立即更新 [英] React hooks state is not updated right after it's set with async
问题描述
设置后是否无法立即获得更新的挂钩值?我假设react只更新下一个渲染的值,因为我的async-await之后的屏幕效果很好.只是日志没有打印出我期望的状态.
Is it not possible to get the updated hook value right after setting it? I assume react only updates value for the next render, since my screen following async-await renders fine. Just logs are not printing out the state I was expecting.
不确定是要记录这样的状态,还是只为需要的状态编写另一个useEffect,然后将console.log放在那里?
Not sure if I'm suppose to log state like this, or write another useEffect just for the states I need and put console.log in there instead?
const [uid, setUID] = useState<string | undefined>(undefined);
const [state, setState] = useState<{ [key: string]: any; } | undefined>();
const load = async () => {
const currentUID = auth().currentUser?.uid;
setUID(currentUID);
console.log(uid); // returns undefined
console.log(currentUID); // this prints fine
await firestore().collection('users').doc(currentUID).get().then(docSnapshot => {
setState(docSnapshot.data());
console.log('Profile: loaded', state); // returns undefined
});
console.log(uid); // returns undefined even after await
console.log('Profile: loaded', state); // returns undefined even after await
}
useEffect(() => {
load();
}, []);
推荐答案
状态更新在内部是异步的,这意味着状态设置程序调用( useState
或 this.setState()
(用于类组件)不会返回承诺.这意味着在其上调用await不会做任何事情,并且await调用之后的同步逻辑在状态更新之前仍将继续运行.
State updates are internally async, meaning state setter calls ( setState()
from useState
or this.setState()
for class components) do not return a promise. This means that calling await on it isn't going to do anything, and synchronous logic after the await call is going to still run before state has been updated.
所以有个解决方法
// Either log it directly in the body of the function
console.log(state);
// ...Or in a useEffect call
useEffect(() => {
console.log(state);
}, [state]);
const handleEvent = e => {
setState(e.target.value);
}
或类组件提供回调.
this.setState({value:newValue},()=> console.log(this.state.value))
这篇关于使用异步设置后,React hooks状态不会立即更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!