我试图通过简单地调用useCustomHooks来创建一个自定义的Hook,以处理来自任何组件的输入HTTP请求,但失败并出现错误
不能在异步函数外使用关键字“ await”
我所做的只是触发http请求自定义组件方法的处理程序
import { useState } from 'react';
import axios from "axios";
const useHttpReqHandler = () => {
const [result, setResult] = useState();
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);
}
return [result, apiMethod];
};
export default useHttpReqHandler;
现在我可以在代码中使用此钩子了,在任何事件处理程序上,只需像这样从钩子返回的callAPI调用
const MyFunc = () => {
const [apiResult, apiMethod] = useHttpReqHandler();
const captchValidation = () => {
const x = result.toString();;
const y = inputValue.toString();;
if ( x === y) {
apiMethod({url: 'some url here', data: {"email": email}, method: 'post'});
alert("success")
}
else {
alert("fail")
}
}
这是正确的方法吗?因为我是Reactjs的初学者
答案 0 :(得分:3)
这是一个有效的版本:
useHttpReqHandler.jsx
import { useState } from 'react';
import axios from "axios";
const useHttpReqHandler = () => {
const [apiResult, setApiResult] = useState();
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);
let responseOK = response && response.status === 200 && response.statusText === 'OK';
if (responseOK) {
const data = await response.data;
console.log(data)
setApiResult(data);
}
}
return [apiResult, apiMethod];
};
export default useHttpReqHandler;
重要的是:
await
结果存储在本地状态(apiResult)
该函数返回一个数组[apiResult,apiMethod]
使用方法:
const [apiResult, apiMethod] = useHttpReqHandler();
apiMethod({url: 'some url here', data: {"email": email}, method: 'post'});
呈现结果:
return {apiResult};
答案 1 :(得分:1)
我认为,最好将.then与Axios一起使用。并尝试为每种方法创建不同的函数“ Get / Post ...”,这是因为在GET方法中您需要使用Effect,但在POST方法中不能相同。在GET方法useHttpReqHandler.js
import { useEffect, useState } from "react";
import axios from "axios";
// GET DATA
const useHttpReqHandler = (url) => {
const [httpData, setHttpData] = useState();
useEffect(() => {
axios
.get(url)
.then((axiosData) => {
// Axios DATA object
setHttpData(axiosData.data);
// you can check what is in the object by console.log(axiosData);
// also you can change the state, call functions...
})
.catch((error) => {
console.log(error);
});
}, []);
return httpData;
};
export default useHttpReqHandler;
在您的main file
import useHttpReqHandler from "...."
const MyFunc = () => {
const getData = useHttpReqHandler("URL");
return (
<div>
...
</div>
)
}
我希望对您有帮助
使用POSt,PUT,DELETE会发生同样的事情……您将为每个处理Http req的方法创建函数