跳到主要内容

异步 Hooks

异步操作相关的 Hooks 集合。

useRequest

用于管理异步请求的 Hook。

import { useRequest } from 'taro-uno';

function Demo() {
const { data, loading, error, run } = useRequest(
() => fetch('/api/user').then(res => res.json()),
{ manual: false }
);

if (loading) return <div>加载中...</div>;
if (error) return <div>错误: {error.message}</div>;

return (
<div>
<p>用户名: {data?.name}</p>
<button onClick={run}>刷新</button>
</div>
);
}

API

参数说明类型默认值
service请求函数(...args: P) => Promise<R>-
options.manual是否手动触发booleanfalse
options.defaultParams默认参数P-
options.onSuccess成功回调(data: R) => void-
options.onError失败回调(error: Error) => void-
options.pollingInterval轮询间隔number-
options.debounceWait防抖等待时间number-
options.throttleWait节流等待时间number-

返回值

参数说明类型
data请求结果R | undefined
loading加载状态boolean
error错误信息Error | undefined
run手动触发请求(...args: P) => Promise<R>
refresh使用上次参数重新请求() => Promise<R>
cancel取消请求() => void

useMutation

用于管理数据变更操作的 Hook。

import { useMutation } from 'taro-uno';

function Demo() {
const { mutate, loading, error } = useMutation(
(data) => fetch('/api/user', {
method: 'POST',
body: JSON.stringify(data),
})
);

const handleSubmit = async () => {
try {
await mutate({ name: 'John' });
console.log('提交成功');
} catch (e) {
console.error('提交失败', e);
}
};

return (
<button onClick={handleSubmit} disabled={loading}>
{loading ? '提交中...' : '提交'}
</button>
);
}

API

参数说明类型
mutationFn变更函数(variables: V) => Promise<R>
options.onSuccess成功回调(data: R) => void
options.onError失败回调(error: Error) => void
options.onSettled完成回调(data: R | undefined, error: Error | undefined) => void

返回值

参数说明类型
mutate触发变更(variables: V) => Promise<R>
loading加载状态boolean
error错误信息Error | undefined
data返回数据R | undefined
reset重置状态() => void