使用React钩子取消HTTP获取请求



这看起来是否是一种合理的方法(如果详细的话(,可以确保每次单击都不会向saveOperation堆栈请求?

我使用RxJS,并将订阅的实例存储在一个可变的ref中,以便它在渲染之间持久存在。然后,如果存在,我会在开始新的之前取消它。

const saveSubscription = useRef<Subscription>(); // RxJS Subscription (cancellable fetch)
const handleChange = () => {
saveSubscription.current?.unsubscribe();
saveSubscription.current = saveOperation({ ...data }).subscribe();
}
...
<input type="text" onClick={() => handleChange()} ref={fileInput} />

解决问题的一种更被动的方法是始终打开订阅并让管道控制数据流。一种方法可能是使用switchMap。

一个随时间变化的异步值是您的文本输入。这可能是外部可观察到的取消订阅内部http请求并启动新的请求:

// Outer text observable that changes via your input
const text$ = new Subject();
// A fake http function to show async http responses
const fakeHttp$ = (text: string) => of('Http answer: ' + text).pipe(delay(1000));
// The http response that can be subscribed to, cancels the fakeHttp request if a new text$ emits within the old open request
const source$ = text$.pipe(
switchMap(fakeHttp$)
);
// Your handle change function that can be called in the JSX Input
handleChange = (text: string) => text$.next(text);

运行堆叠式

最新更新