useState回调函数执行后,状态值没有发生改变?

3

我只想在错误状态下添加错误信息。但是当发生错误时,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 };
}


2
小问题,为什么你要使用两个 componentDidMount?你可以合并它们,并从第一个函数中返回清理函数。 - Rajesh
你尝试在catch语句处设置断点并查看它是否会抛出错误了吗?你的API发送的是什么HTTP错误代码?404?500? - Kevin Moe Myint Myat
当你从catch中重新抛出错误时,会发生什么?你很可能会终止线程。 - lux
似乎对我来说正在更新:https://codesandbox.io/s/pedantic-nash-thied?file=/src/App.js。你能分享一下你看到状态没有更新的部分吗? - Shadab
你是如何验证“error”状态没有被更新的?你能否更新你的问题,包括使用这个自定义钩子的示例组件来重现这个问题? - Drew Reese
@KevinMoeMyintMyat 后端代码中我写了出现了400错误。 - MD Jahid Hasan
1个回答

1
作为你的后端正在响应 JSON,这意味着响应状态码可能是 200(成功)。这使得 "response.ok" 为真。
你需要查看返回的 JSON 字符串以获取有效数据或错误消息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接