简体   繁体   English

获取数据并更新 isLoading 但 setState 没有正确更新,它总是最终成为初始 isLoading state

[英]Fetching data and updating the isLoading but setState isn't updating correctly and it always ends up being the initial isLoading state

const App = () => {
    const [user, setUser] = useState({
        name: "",
        organisationName: "",
        id: "",
        isLoading: false,
    });
    useEffect(() => {
        const userId = getUserIdFromParams();
        if (userId) {
            setUser({...user, isLoading: true}); // dispatch(STARTED_FETCHING_LEAD)
            (async () => {
                const retrievedUser = await getLeadFromDatabase(leadId);
                if (retrievedUser) setUser({...user, ...retrievedUser});
            })();
        }
        setUser({...user, isLoading: false});
    }, []);

What I expect to happen is the following:我期望发生的情况如下:

if there is userId in the URL parameters, isLoading is set to true (component updates accordingly).如果 URL 参数中有 userId,则 isLoading 设置为 true(组件相应更新)。 Then when a user is retrieved, the state will be set to the user details and then finally the state is updated one last time to isLoading false.然后当检索到用户时,state 将设置为用户详细信息,最后 state 最后一次更新为 isLoading false。

What happens:怎么了:

State doesn't update accordingly and it always ends up being the same state as the one set in useState. State 不会相应地更新,它总是最终与 useState 中的一组相同的 state。 So if I set isLoading: true in the original state.因此,如果我在原始 state 中设置 isLoading: true。 The loading component will be shown indefinitely, when I set to false it ends up being false.加载组件将无限期显示,当我设置为 false 时,它最终为 false。

Anyone has any idea what's going on here?有人知道这里发生了什么吗? All help is much appreciated:)非常感谢所有帮助:)

  1. You don't need to write setUser({...user, isLoading: true}) you can just say setUser({ isLoading: true }) see the docs你不需要写setUser({...user, isLoading: true})你可以说setUser({ isLoading: true })查看文档

  2. You retrieve the user asynchronously but reset isLoading to true synchronously.您异步检索用户,但同步重置isLoading为 true。 So isLoading will most likely be false before the user is loaded.因此,在加载用户之前, isLoading很可能是错误的。 I would rewrite it like this:我会这样重写它:

useEffect(() => {
    const userId = getUserIdFromParams();
    if (userId) {
        setUser({...user, isLoading: true}); // dispatch(STARTED_FETCHING_LEAD)
        (async () => {
            const retrievedUser = await getLeadFromDatabase(leadId);
            if (retrievedUser) setUser({...retrievedUser, isLoading: false});
        })();
    }
}, []);

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

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