首页 > 解决方案 > 为什么使用带有 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 是错误的。应该是真的。

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

标签: javascriptreactjs

解决方案


推荐阅读