我只想在错误状态下添加错误消息。但是,当发生错误时,setError不会更改,就不会添加错误消息。后端以json格式{“ error”:“ error message”}的形式给出错误消息,如果我在控制台日志中,该错误可以正常运行,但错误状态不会更新。
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 };
}
答案 0 :(得分:1)
当您的后端使用JSON进行响应时,这意味着响应状态代码可能为200(成功)。这使“ response.ok”正确。
您将必须查看返回的JSON字符串以获取有效数据或错误消息。