setstate 回调后 useState 没有改变?
useState does not changing after setstate callback?
我只想在错误状态下添加错误信息。但是当错误发生时,setError does not changing 意味着不添加错误信息。后端以 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 字符串以获取有效数据或错误消息。
我只想在错误状态下添加错误信息。但是当错误发生时,setError does not changing 意味着不添加错误信息。后端以 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 字符串以获取有效数据或错误消息。