reactjs - 如何使用 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 不可分配给布尔类型”时,值道具也会出错
有人可以帮我解决这个问题。谢谢
解决方案
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
}
推荐阅读
- mesh - 如何使用 gmsh 获得更规则的曲面四边形?
- javascript - 写入同一个 JSON 文件后无法读取 JSON 文件
- java - 如何在 Java 中使用 SVM 关于 Android 应用程序
- firebase - 关于带有firebase的签名发布flutter应用程序的问题
- python - 日期时间类型对象的 SQLAlchemy 查询速度慢
- karate - 是否有类似 JsonObject 的“包含”等价物(不仅仅是 JsonArray)?
- javascript - 如何将多个axios调用链接在一起,使它们同步运行,并且每次调用都可以使用上一次调用返回的数据
- regex - Perl 正则表达式意外的性能下降
- python - Python Pandas:如果列表列表中的项目与熊猫中的列行匹配,则添加新列
- sql-server - 如何根据另一个表中不存在的数据更新一个表中的行?