跳到主要内容

中断请求

通过 useHook 接收abort用于手动中断请求。

// useRequest
const {
// ...
// abort函数用于中断请求
abort
} = useRequest(todoListGetter);

// useWatcher
const {
// ...
// abort函数用于中断请求
abort
} = useWatcher(todoListGetter, [page]);

然后再调用abort方法即可中断请求。

const handleCancel = () => {
abort();
};

[2.9.0+] 在 react 中,abort 函数使用了useCallback包裹,同时它也不受闭包陷阱限制,你可以直接在事件中使用它,不用担心引起性能问题。

[2.6.2+] 另外,这个abort函数也会同时绑定到当前的 method 实例上,因此通过useRequest/useWatcher发送的请求,也可以这样来中断请求。

const todoListGetter = alovaInstance.Get('todo/list');
useRequest(todoListGetter);
useWatcher(() => todoListGetter);

// 调用method上的abort也可以中断请求
const handleCancel = () => {
todoListGetter.abort();
};

因此,如果需要实现在满足一定条件时批量中断请求,还可以在beforeRequest中调用abort中断请求。

const alovaInst = createAlova({
// ...
beforeRequest(method) {
if (someCondition) {
method.abort();
}
}
});