为什么使用useState和react和typescript不能将状态设置为true?

时间:2020-06-09 18:44:07

标签: javascript reactjs

我想使用react useState将加载状态设置为true。

我要做什么? 我想在获取请求时显示加载指示器。我是通过在请求开始之前将loading state设置为true,并在请求结束后立即将load state设置为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为false。应该是真的。

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

0 个答案:

没有答案