gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:26:02 24 4
gpt4 key购买 nike

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

例如,如果我有一个名为 userState 的原子,并且我更新了它的一个属性,如 avatar_url,如果我在设置用户。

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有关,更新值可用on the next render因为 setState(Recoil 的基础)是异步的。

setState() does not immediately mutate this.state but creates apending state transition. Accessing this.state after calling thismethod can potentially return the existing value. There is noguarantee of synchronous operation of calls to setState and calls maybe batched for performance gains.

你应该使用 useEffect 来模拟这个行为:

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

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

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

关于reactjs - React/Recoil - setAtom 新值何时可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64520432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com