【问题标题】:Axios request in react for handling http request用于处理http请求的axios请求
【发布时间】:2023-10-19 10:24:01
【问题描述】:

反应中的axios请求

这是我的自定义钩子,但在等待响应时我不知道如何附加微调器 我添加了加载并将其设置为 true 进一步我注意到解决它

const useHttpReqHandler = () => {
    const [result, setResult] = useState();
    const [loading, setLoading] = useState(true);

    const apiMethod = async ({url , data , method}) => {
        let options = {
            method,
            url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data
        };
        let response = await axios(options);
        const UpdatedData = await response.data;
        console.log(UpdatedData)
        setResult(UpdatedData);
        setLoading(false)
    }

    return [result , apiMethod];
};

我在另一个组件下调用这个自定义钩子

但是如何在等待响应时添加 Sppiner

【问题讨论】:

  • 显示您的微调器代码
  • 也从钩子中返回loading
  • 嗨@Eugen Sunic 我无法附加微调器代码我应该在哪里附加我对逻辑感到困惑

标签: javascript reactjs axios react-hooks


【解决方案1】:
const useHttpReqHandler = () => {
    const [result, setResult] = useState();
    const [loading, setLoading] = useState(false);

    const apiMethod = useCallback(async ({url , data , method}) => {
        let options = {
            method,
            url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data
        };

        setLoading(true);


        try {
          let response = await axios(options);
          const UpdatedData = await response.data;
          setResult(UpdatedData);

          setLoading(false);
        } catch (e) {
          console.error(e)
          setLoading(false);
        }

    }, [setLoading, setResult])

    return [loading, result , apiMethod];
};

然后在您的组件中显示一个微调器,而 loadingtrue

未经测试,可能无法正常工作,但您可能会明白:

const MyComponent = () => {
    const [loading, apiResult,  apiMethod] = useHttpReqHandler();


    const captchValidation = useCallback(() => {
        const x = result.toString();
        const y = inputValue.toString();

        apiMethod({url: 'your url', data: {"email": email}, method: 'post'})

        if (x === y) {
            console.log("Entered here in api part")
            if(apiResult){
             alert("success")
            }
        }
        else {
             alert("fail")
        }
    }, [apiMethod, apiResult])

    return (
        <>
            {
                loading ? (<Spinner />) : (<button onClick={captchValidation}></button>)
            }
        </>
    )
}

【讨论】:

  • 嗨@Lekoaf 我很困惑如何在我提到的函数 captchValidation() 中使用这个钩子
  • 你不能在实用函数中使用 Hooks。它必须是一个 React 组件。
  • 添加了一个粗略的例子。
  • 这个粗略的例子运行良好,非常感谢老板@Lekoaf,但编译错误抛出这个 React Hook useCallback 缺少依赖项:'email'、'inputValue' 和 'result'。要么包含它们,要么移除依赖数组
  • 是的,我不知道你从哪里得到的。我并没有真正从您的代码中删除任何内容。以某种方式将它们安装在其中取决于您。
最近更新 更多