javascript - 为什么使用带有 react 和 typescript 的 useState 未将状态设置为 true?
问题描述
我想使用 react useState 将加载状态设置为 true。
我想做什么?我想在获取请求时显示加载指示器。我通过在请求开始之前将加载状态设置为 true 并在请求结束后不久将加载状态设置为 false 来做到这一点。
下面是我的代码,
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);
console.log('loading state b4', isLoading); //this logs loading to false
load().then(() => {
setIsLoading(false);
});
}
}
}
function Parent () {
useAnother('21s');
return (
//some jsx here
);
}
现在的问题是我不确定为什么在记录时 isLoading 是错误的。应该是真的。
有人可以帮我解决这个问题。谢谢。
解决方案
推荐阅读
- python - Just Once 类实例化、Singletone、@cache、@memoize、__new__,导致 sameInstance——我们当前的最佳实践应该是什么?
- javascript - Three.js - Shadow.bias 修复阴影静态,但移动阴影。怎么修?
- c++ - 2 个 int8_t 到 uint16_t 并返回
- javascript - 如果我更改变量的值,原始值是否仍然存在于内存中?
- c - GCC/ld 不使用带有 -l 的共享对象
- python - 使用循环逻辑以 dd/mm/22 格式打印 2022 年的日期列表
- python - 从图像中消除失真(相机校准后)的问题
- ios - 检测应用程序是否通过点击本地通知 Swift 启动
- python - TypeError: read_excel() 在使用 pandas 将单个 excel 行导出到 json 文件时得到了一个意外的关键字参数“索引”
- python - scikit 管道的问题(不填充 NaN)