React / Recoil - setAtom 新值何时可用?

React / Recoil - when is setAtom new value available?

我正在尝试了解 React Recoil 以及更新的原子值何时可用,或者如何使新值在应用程序中垂直和水平传播。

例如,如果我有一个名为 userState 的原子,并且我更新了它的一个属性,例如 avatar_url,如果我在 setUser 之后立即控制它,那么该值不是新值。

const [user, setUser] = useRecoilState(userState);

setUser({ avatar_url: imageURL, ...appUser});

console.log(imageURL); // is the actual new URL
console.log(user.avatar_url); // should be new URL but isn't

它与 Recoil 无关,但与 React 相关,更新后的值可用 因为 setState(Recoil 的基础)是异步的。

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

您应该使用 useEffect 来模拟此行为:

const [user, setUser] = useRecoilState(userState);

setUser({ avatar_url: imageURL, ...appUser});

useEffect(() => {
  console.log(user.avatar_url);
}, [user]);