【发布时间】:2020-06-10 07:22:56
【问题描述】:
我想在主组件的每个组件中访问 isLoading 状态。基本上,当 useAnother 钩子中的 load() 开始和结束时,我将加载状态设置为 true 和 false。
下面是我没有上下文提供者的代码,
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);
});
}
}
}
function Main ({user}: Props) {
useAnother(user.id); //fetching isLoading here from useHook
return (
<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>
);
}
现在使用上下文提供程序
interface LoadingContextState {
isLoading: boolean;
setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;
}
const initialLoadingState: LoadingContextState = {
isLoading: false, setIsLoading: () => {},
};
export const LoadingContext = React.createContext<LoadingContextState>(
initialLoadingState
);
export const LoadingContextProvider: React.FC = ({ children }) => {
const [isLoading, setIsLoading] = React.useState<boolean>(false);
return (
<LoadingContext.Provider
value={{
isLoading,
setIsLoading,
}}
>
{children}
</LoadingContext.Provider>
);
};
function App() {
return (
<LoadingContextProvider>
<Main/>
</LoadingContextProvider>
);
}
function useAnother(Id: string) {
const [compId, setCompId] = React.useState(undefined);
const {setIsLoading} = React.useContext(LoadingContext);
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);
});
}
}
}
function Main ({user}: Props) {
useAnother(user.id);
return (
<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>
);
}
function FirstComponent () {
const {isLoading} = React.useContext(LoadingContext);
return (
<Wrapper isLoading={isLoading}/>
);
}
这行得通。但我不想使用上下文提供程序,是否可以为此使用钩子而不是上下文。
有人可以帮我解决这个问题吗?谢谢。
}
现在使用上下文提供程序
interface LoadingContextState {
isLoading: boolean;
setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;
}
const initialLoadingState: LoadingContextState = {
isLoading: false, setIsLoading: () => {},
};
export const LoadingContext = React.createContext<LoadingContextState>(
initialLoadingState
);
【问题讨论】:
标签: reactjs typescript