当使用钩子单击表单提交按钮时,如何调用API,然后将其JSON结果存储到某个状态?
在下面的代码中,我使用了一个form。当用户单击submit按钮时,将根据他们提供的参数调用API,但当我尝试以某种状态存储它时,我得到以下错误
import {useForm} from "react-hook-form";
import {useState, useEffect} from "react";
function Example() {
const {register, handleSubmit} = useForm();
const [storage, setStorage] = useState(null)
const submitAction = async(data) => {
let url = "..."
url += data.param
useEffect(async () => {
setStorage(response.data...)
}, [])
}
return (
<div>
<form onSubmit = {handleSubmit(submitAction)}>
<select {...register('param')}>
<option value="something"> something </option>
...
</select>
<button type={"submit"}submit</button>
</form>
</div>
)
}Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.我一直在关注this post,据我所知,useEffect(...)必须排在submitAction之前。在useEffect中,我根据一个布尔变量call API if boolean var = true锁定API调用。但是我不确定我应该如何传递API所需的参数。
发布于 2021-10-17 12:33:20
您应该定义async函数,然后在useEffect或onEvent中使用它们。
同时使用async和await。
import {useState, useEffect} from "react";
import axios from axios;
const Component = () => {
const fetchData = async () => {
try {
const { data } = await axios.get/post(...);
} catch (e) {
console.log(e)
}
};
useEffect(() => {
fetchData();
}, []);
}如果您想通过单击来调用API
HTML
<form onSubmit={fetchData}>
...
</form>Javascript
import {useState, useEffect} from "react";
import axios from axios;
const Component = () => {
const [data, setData] = useState([]);
const fetchData = async (e) => {
e.preventDefault();
try {
const { data } = await axios.get/post(...);
} catch (e) {
console.log(e)
}
};
}https://stackoverflow.com/questions/69604209
复制相似问题