如何解决setState回调后useState不会改变吗?
我只想在错误状态下添加错误消息。但是,当发生错误时,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 };
}
解决方法
当您的后端使用JSON进行响应时,这意味着响应状态代码可能为200(成功)。这使“ response.ok”正确。
您将必须查看返回的JSON字符串以获取有效数据或错误消息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。