请求时序的问题还挺常见的,比如你发现请求 loading 的控制不对,数据不对(没有 cancel 机制),通常都是请求时序的问题。
处理方式的逻辑很简单,就是要想办法知道,请求响应回来时,该响应是不是最新的发出请求。借用闭包机制即可。
比如在 React 中,可以如下解决
function App() {
const [fetching, setFetching] = React.useState(false);
const [options, setOptions] = React.useState<ValueType[]>([]);
const fetchRef = React.useRef(0);
const debounceFetcher = React.useMemo(() => {
const loadOptions = (value: string) => {
fetchRef.current += 1;
const fetchId = fetchRef.current;
setOptions([]);
setFetching(true);
fetchOptions(value).then(newOptions => {
if (fetchId !== fetchRef.current) {
// for fetch callback order
return;
}
setOptions(newOptions);
setFetching(false);
});
};
return debounce(loadOptions, debounceTimeout);
}, [fetchOptions, debounceTimeout]);
}