忽略以前的异步调用并执行最新的调用



我正在使用React、

我有一个按钮,可以在每个onClick事件上调用异步函数:

<MyButton onClick={handleClick}>
Next
</MyButton>

然后是一个加载数据需要时间的函数:

const isExecuting = useRef(false);
const handleClick = async () => {
if (!isExecuting.current) {
isExecuting.current = true;
try {
resetViews();
await chargeViews(patientId);
} finally {
isExecuting.current = false;
}
}
};

因此,例如,当我点击5次时,它将接收5个调用,并且所有调用都将按顺序执行,我需要一种方法来只执行最近的调用,而忽略之前的4个调用,这样就不需要时间来执行所有调用。

PS:我曾想过在功能执行完成之前禁用该按钮,但由于我正在使用该按钮加载下一个patient,这将不方便,因为我们必须等待4名患者加载才能加载第5名患者。

Debounce是一个选项,该选项是传递ref并获取它cancelToken。当您试图再次点击同一个API时,它将取消以前的调用如果存在并调用新的API请求,下面的示例是一般解决方案,或者您可以从组件发送cancelToken并在新的API调用之前调用它

// dummy Api
const chargeViews = async (sourceRef,patientId) => {
console.log({patientId})
try {
let token = undefined;
if (sourceRef) {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
token = { cancelToken: source.token };
sourceRef.current = source;
}
const response = await Axios.get(`endpointURL`, token)
return response.data;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
throw new Error(err);
}
};

组件

const sourceRef = React.useRef(null);
const handleClick = async () => {
try {
if (sourceRef.current) sourceRef.current.cancel();
await chargeViews(sourceRef, patientId);
} catch (error) {
console.log(error)
}
};
<MyButton onClick={handleClick}>
Next
</MyButton>

最新更新