Axios请求在响应中处理HTTP请求

时间:2020-04-22 11:47:56

标签: javascript reactjs axios react-hooks

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

1 个答案:

答案 0 :(得分:2)

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>)
            }
        </>
    )
}