最佳答案
我正在创建一个页面,用户可以用 React-Hook-Form 更新个人数据。
一旦加载了分页,我就使用 useEffect
来获取用户当前的个人数据,并将它们设置为表单的默认值。
我将提取的值放入 <Controller />
的 defaultValue
中。
但是,它只是没有显示在文本框中。
这是我的代码:
import React, {useState, useEffect, useCallback} from 'react';
import { useForm, Controller } from 'react-hook-form'
import { URL } from '../constants';
const UpdateUserData = props => {
const [userData, setUserData] = useState(null);
const { handleSubmit, control} = useForm({mode: 'onBlur'});
const fetchUserData = useCallback(async account => {
const userData = await fetch(`${URL}/user/${account}`)
.then(res=> res.json());
console.log(userData);
setUserData(userData);
}, []);
useEffect(() => {
const account = localStorage.getItem('account');
fetchUserData(account);
}, [fetchUserData])
const onSubmit = async (data) => {
// TODO
}
return (
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>User Name:</label>
<Controller
as={<input type='text' />}
control={control}
defaultValue={userData ? userData.name : ''}
name='name'
/>
</div>
<div>
<label>Phone:</label>
<Controller
as={<input type='text' />}
control={control}
defaultValue={userData ? userData.phone : ''}
name='phone'
/>
</div>
<button>Submit</button>
</form>
</div>
);
}
export default UpdateUserData;
被调用的 API 工作正常,值实际上被设置为 userData
状态。
{
name: "John",
phone: "02-98541566"
...
}
我还尝试使用 useEffect()
中的模拟数据使用 setUserData
,但它也不能工作。
我上面的代码有什么问题吗?