跳到主要内容

useLoading()

帮助追踪命令式异步函数的加载与错误状态。

提示

对于 GET/读取类 endpoint,useSuspense() 或 useDLE() 更合适。

用法​

import { useLoading, useController } from '@data-client/react';
import { PostResource } from './PostResource';
import PostForm from './PostForm';

export default function PostCreate() {
  const ctrl = useController();
  const navigate = useNavigate();
  const [handleSubmit, loading, error] = useLoading(
    async data => {
      const post = await ctrl.fetch(PostResource.getList.push, data);
      navigate(`/posts/${post.id}`);
    },
    [ctrl, navigate],
  );
  return (
    <PostForm onSubmit={handleSubmit} loading={loading} error={error} />
  );
}
实时预览

与 useCallback 一样,它接收一个依赖列表,以确保函数的引用一致性。

Eslint​

Eslint 配置

由于我们使用了依赖列表,如果你使用 react-hooks/exhaustive-deps 规则,请务必将 useLoading 添加到该规则的 'additionalHooks' 配置中。

{
"rules": {
// ...
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "(useLoading)"
}]
}
}

类型​

export default function useLoading<
F extends (...args: any) => Promise<any>,
>(func: F, deps: readonly any[] = []): [F, boolean, Error | undefined];

在返回的 promise 处于 pending 状态时,loading 为 true。如果 func reject,该 rejection 会被捕获并存入 error;下次调用时会再次被清除。当调用相互重叠时,loading 和 error 跟随最近一次调用,因此较早发起但较晚完成的调用不会改变它们。

示例​

Github 分页​

探索 github-app 示例

更多演示

Github 评论表单提交​

探索 github-app 示例

更多演示