我只想在错误状态下添加错误信息。但是当发生错误时,setError不会发生更改,也就是说不会添加错误消息。后端以json格式提供错误消息{ "error": "错误消息" },如果我将该错误记录到控制台,则可以正常工作,但错误状态不会更新。
import { useState, useCallback, useRef, useEffect } from 'react';
export const useHttpClient = () => {
const [ isLoading, setIsLoading ] = useState(false);
const [ error, setError ] = useState();
const activeHttpRequests = useRef([]);
const sendRequest = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
setIsLoading(true);
const httpAbortCtrl = new AbortController();
activeHttpRequests.current.push(httpAbortCtrl);
try {
const response = await fetch(url, {
method,
body,
headers,
signal: httpAbortCtrl.signal
});
const responseData = await response.json();
activeHttpRequests.current = activeHttpRequests.current.filter(
reqCtrl => reqCtrl !== httpAbortCtrl
);
if(!response.ok) {
throw new Error(responseData.error);
}
setIsLoading(false);
return responseData;
} catch (e) {
setError(e.message);
setIsLoading(false);
throw e;
}
}, []);
const clearError = () => {
setError(null);
};
useEffect(() => {
//this runs as cleanup function before next time useEffect run or also when an component use useEffect unmount
return () => {
activeHttpRequests.current.forEach(aboutCtr => aboutCtr.abort());
}
}, []);
return { isLoading, error, sendRequest, clearError };
}
componentDidMount
?你可以合并它们,并从第一个函数中返回清理函数。 - Rajeshcatch
中重新抛出错误时,会发生什么?你很可能会终止线程。 - lux