我想在输入字段中使用react-hook-form
. 首先,我从 API 端点检索用户数据,然后将状态设置users
为该用户数据。然后我将状态传递users
给defaultValues
of useForm()
。
import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import axios from "axios";
function LoginFile() {
const [users, setUsers] = useState(null);
useEffect(() => {
axios
.get("http://localhost:4000/users/1")
.then((res) => setUsers(res.data));
}, []);
useEffect(() => {
console.log(users);
}, [users]);
const { register, handleSubmit, errors } = useForm({
defaultValues: users,
});
return (
<div>
<form onSubmit={handleSubmit(onSubmit)}>
Email <input type="email" name="email" ref={register} /><br />
firstname <input name="firstname" ref={register} /><br/>
<input type="submit" />
</form>
</div>
);
}
export default LoginFile;
我按照上面的代码做了,但没有按预期工作。所有输入字段仍然是空的。我想在表单的输入字段中有一些默认值。