如何通过react和Typescript使用usecontext?

时间:2020-06-09 21:42:35

标签: reactjs typescript

我想在由上下文提供程序包装的组件的子组件中使用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不能分配给类型为'context'**的参数

在我使用LoadingContext.Provider“类型无效不能分配为布尔型”的值道具时也得到错误

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

1 个答案:

答案 0 :(得分:0)

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
}