Home Article Practice 取消数据请求

取消数据请求

2024-07-06 18:58  views:234  source:许某    

React中的一种很常见的问题是:如果在组件中发送一个请求,
在请求还没有返回的时候卸载了组件,这个时候还会尝试设置这个状态,
会报错。我们需要在hooks中处理这种情况,可以看下是怎样处理的:
const useDataApi = (initialUrl, initialData) => {
const [url, setUrl] = useState(initialUrl);
const [state, dispatch] =
useReducer(dataFetchReducer, {
isLoading: false,
isError: false,
data: initialData,
});
useEffect(() => {
let didCancel = false;
const fetchData = async () => {
dispatch({ type: 'FETCH_INIT' });
try {
const result = await axios(url);
if (!didCancel) {
dispatch({ type: 'FETCH_SUCCESS',
payload: result.data });
}
} catch (error) {
if (!didCancel) {
dispatch({ type: 'FETCH_FAILURE' });
}
}
};
fetchData();
return () => {
didCancel = true;
};
}, [url]);
const doFetch = url => {
setUrl(url);
};
return { ...state, doFetch };
};
我们可以看到这里新增了一个didCancel变量,如果这个变量为true,
不会再发送dispatch,也不会再执行设置状态这个动作。
这里我们在useEffe的返回函数中将didCancel置为true,在卸载组件时会自动调用这段逻辑。
也就避免了再卸载的组件上设置状态。



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)