useLoading()
帮助追踪命令式异步函数的加载与错误状态。
提示
对于 GET/读取类 endpoint,useSuspense() 或 useDLE() 更合适。
用法
PostResource
PostDetail
PostForm
PostCreate
Navigation
import { useLoading, useController } from '@data-client/react'; import { PostResource } from './PostResource'; import PostForm from './PostForm'; export default function PostCreate({ navigateToPost }) { const ctrl = useController(); const [handleSubmit, loading, error] = useLoading( async data => { const post = await ctrl.fetch(PostResource.getList.push, data); navigateToPost(post.id); }, [ctrl], ); return ( <PostForm onSubmit={handleSubmit} loading={loading} error={error} /> ); }
结果
Store▶
与 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];
示例
Github 分页
探索 github-app 示例
Github 评论表单提交
探索 github-app 示例