代码之家  ›  专栏  ›  技术社区  ›  memelord23

如何使上下文在创建之前获取数据?

  •  0
  • memelord23  · 技术社区  · 2 年前

    我正在尝试实现一个加载页面。我有两个上下文,它们都需要GET请求来加载信息。一个用于身份验证,另一个用于获取当前用户配置文件状态。两者都使用 useEffect 以获取数据。

    例如,Profile上下文 使用效果 看起来是这样的。

        ...
        const [loading, setLoading] = useState(true);
    
        useEffect(() => {
            getProfile()
                ...
                setLoading(false);
            
        }, [])
    

    我的主要上下文是这样的,

    export const AppContextComponent: React.FC<Props> = ({ children }) => {
        const authContext = useAuthContext();
        const profileContext = useProfileContext();
    
        const isLoading = authContext.loading || profileContext.loading;
    
        if (isLoading) {
            return <div> Loading... </div>;
        }
    
        return (
            <AuthContextComponent>
                <ProfileContextComponent>
                    { children } 
                </ProfileContextComponent>
            </AuthContextComponent>
        )
    }
    

    现在,我遇到的问题是,两个子上下文都将其“加载”状态初始化为True,因为它们被初始化为True isLoading 在顶级上下文中将为True。但是,因为我从不创建上下文组件 使用效果 将永远不会被调用以发出GET请求,并在稍后将加载状态更改为 False .

    可以打电话给吗 使用效果 以便发出GET请求并将加载状态更新为False,同时仍然不“创建它”,因为我想返回我的加载页面。

    1 回复  |  直到 2 年前
        1
  •  0
  •   Nick Vu    2 年前

    您可以创建另一个具有加载逻辑的组件,然后在上下文初始化后调用该组件。

    export const LoadingComponent = React.FC<Props> = ({ children }) => {
        const authContext = useAuthContext();
        const profileContext = useProfileContext();
    
        const isLoading = authContext.loading || profileContext.loading;
    
        if (isLoading) {
            return <div> Loading... </div>;
        }
    
        return children
    }
    
    export const AppContextComponent: React.FC<Props> = ({ children }) => {
        return (
            <AuthContextComponent>
                <ProfileContextComponent>
                    <LoadingComponent>
                        { children } 
                    </LoadingComponent>
                </ProfileContextComponent>
            </AuthContextComponent>
        )
    }