【问题标题】:useState does not changing after setstate callback?setstate 回调后 useState 不改变?
【发布时间】:2020-12-10 12:01:39
【问题描述】:

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

【问题讨论】:

  • 小问题,你为什么 2 componentDidMount?您可以合并两者并从第一个本身返回清理函数
  • 您是否尝试在 catch 语句处下断点,看看它是否会引发错误。您的 API 发送的 http 错误代码是什么? 404? 500?
  • catch 重新抛出后会出现什么错误?您可能正在杀死线程。
  • 对我来说似乎正在更新:codesandbox.io/s/pedantic-nash-thied?file=/src/App.js。你能分享一下你看到状态没有更新的部分吗?
  • 您如何验证/确认“错误”状态未更新?您能否更新您的问题以包含使用此自定义钩子重现问题的示例组件?

标签: javascript reactjs react-hooks fetch react-state


【解决方案1】:

由于您的后端使用 JSON 进行响应,这意味着响应状态代码可能是 200(成功)。这使得“response.ok”为真。

您必须查看返回的 JSON 字符串以获取有效数据或错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多