错误重试
通过设置 options.retryCount
,指定错误重试次数,则 useRequest 在失败后会进行重试。
const { data, run } = useRequest(getUsername, {
retryCount: 3,
});
如上示例代码,在请求异常后,会做 3 次重试。
你可以在下面 input 框中输入文本,并点击 Edit 按钮,体验效果
- React
- Vue
network/useRequest/retry/index
import React from 'react';
import DemoContent from '@src/components/DemoContent';
import { Button, Field, Input } from '@taroify/core';
import { useRequest } from 'taro-hooks';
import { showToast } from '@tarojs/taro';
import { useState } from '@taro-hooks/core';
function editUsername(username: string) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Failed to modify username'));
}, 1000);
});
}
export default () => {
const [state, setState] = useState('');
const { loading, run } = useRequest(editUsername, {
retryCount: 3,
manual: true,
onError: (error) => {
showToast({
title: error.message,
icon: 'error',
mask: true,
});
},
});
return (
<DemoContent title="错误重试">
<Field align="center">
<Input
onChange={(e) => setState(e.detail.value)}
value={state}
placeholder="Please enter username"
/>
<Button
loading={loading}
color="primary"
size="small"
onClick={() => run(state)}
>
{loading ? 'Loading' : 'Edit'}
</Button>
</Field>
</DemoContent>
);
};
network/useRequest/retry/index
<template>
<block>
<demo-content title="错误重试">
<nut-input
:disabled="request.loading"
v-model="state"
placeholder="Please enter username"
>
<template #button>
<nut-button
:loading="request.loading"
size="small"
type="primary"
shape="square"
@click="request.run(state)"
>{{ request.loading ? 'Loading' : 'Edit' }}</nut-button
>
</template>
</nut-input>
</demo-content>
</block>
</template>
<script>
import { showToast } from '@tarojs/taro';
import { useState } from '@taro-hooks/core';
import { useRequest } from 'taro-hooks';
function editUsername(username) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Failed to modify username'));
}, 1000);
});
}
export default {
setup() {
const [state] = useState('');
const request = useRequest(editUsername, {
retryCount: 3,
manual: true,
onError: (error) => {
showToast({
title: error.message,
icon: 'error',
mask: true,
});
},
});
return {
request,
state,
};
},
};
</script>
API
Options
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
retryCount | 错误重试次数。如果设置为 -1 ,则无限次重试。 | number | - |
retryInterval |
| number | - |
备注
options.retryCount
、options.retryInterval
支持动态变化。cancel
可以取消正在进行的重试行为。