首页 > 解决方案 > 如何使用 react 和 typescript 使用 usecontext?

问题描述

我想在使用上下文提供程序包装的组件的子组件中使用 usecontext。

我想在父组件的 useAnother 钩子中设置加载状态,然后让所有子组件都可以访问加载状态。

下面是我的代码,

export function useLoad() {
    const { refetch: refetchItems } = useGetItems();
    const { refetch: refetchOwnedItems } = useListOwnedItems();
    return async function() {
        await refreshCompany();
        refetchItems();
        refetchOwnedItems();
    };  
}

function useAnother(Id: string) {
    const [compId, setCompId] = React.useState(undefined);
    const [isLoading, setIsLoading] = React.useState(false);
    const comp = useCurrentComp(Id);
    const load = useLoad();
    if (comp && comp.id !== compId) {
        setCompId(comp.id);
        const prevCompId = compId !== undefined;
        if (prevCompId) {
            setIsLoading(true);
            load().then(() => {
                setIsLoading(false);
            });
        }
    }
} 

export const LoadingContext = React.createContext(true); 

function Main ({user}: Props) {
    const isLoading = useAnother(user.id); //fetching isLoading here from useHook
    return (
        <LoadingContext.Provider value={isLoading}> //also here error type                      void is not assignable to type boolean
            <Wrapper>
                <React.suspense>
                    <Switch>
                        <Route 
                            path="/" 
                            render={routeProps => (
                                <FirstComp {...routeProps} />
                            )}
                        />
                        <Route 
                            path="/items" 
                            render={routeProps => (
                                <SecondComp {...routeProps} />
                            )}
                        />
                        //many other routes like these
                    </Switch>
                </React.suspense>
            </Wrapper>
        </LoadingContext.Provider>
    );
}

function FirstComponent () {
    const isLoading = React.useContext(LoadingContext); //this throws error
}

在 FirstComponent 中访问 isLoading 会引发错误

({user}: props) 类型的参数 => 元素或 null 不能分配给“上下文”类型的参数**

在我使用 LoadingContext.Provider “类型 void 不可分配给布尔类型”时,值道具也会出错

有人可以帮我解决这个问题。谢谢

标签: reactjstypescript

解决方案


useAnother(user.id);未按boolean要求返回createContext(true);

function useAnother(Id: string) {
    const [compId, setCompId] = React.useState(undefined);
    const [isLoading, setIsLoading] = React.useState(false);
    const comp = useCurrentComp(Id);
    const load = useLoad();
    if (comp && comp.id !== compId) {
        setCompId(comp.id);
        const prevCompId = compId !== undefined;
        if (prevCompId) {
            setIsLoading(true);
            load().then(() => {
                setIsLoading(false);
            });
        }
    }

    return isLoading
}

推荐阅读