我只想在错误状态下添加错误消息。但当错误发生时,setError不改变意味着不添加错误消息。后端以json格式给出错误消息{"错误":"错误消息"},如果我控制台记录该错误,则该错误工作正常,但错误状态未更新。
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 };
}
由于后端使用JSON进行响应,这意味着响应状态代码可能为200(成功(。这使得";响应ok";是的。
您必须查看返回的JSON字符串以查找有效数据或错误消息。