繁体   English   中英

React hooks state 在异步设置后不会立即更新

[英]React hooks state is not updated right after it's set with async

设置后是否无法立即获取更新的挂钩值? 我假设 react 只更新下一次渲染的值,因为我的屏幕在 async-await 之后渲染得很好。 只是日志没有打印出我期待的 state。

不确定我是否应该像这样记录 state ,还是只为我需要的状态编写另一个 useEffect 并将 console.log 放在那里?

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();
}, []);

State updates are internally async, meaning state setter calls ( setState() from useState or this.setState() for class components) do not return a promise. 这意味着在它上面调用 await 不会做任何事情,并且 await 调用之后的同步逻辑将在 state 更新之前仍然运行。

所以有一个修复

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

或者 class 组件提供回调。

this.setState({value: newValue}, () => console.log(this.state.value))

在这里阅读更多

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM