[英]useEffect is not updating the default value of react-hook-form when creating edit form
I´m trying to populate the values of material-ui datepicker fields when rendering the edit form component, I can see in the console that the date object is being created correctly, but its not passing to the state, dont know what i´m doing wrong.我正在尝试在呈现编辑表单组件时填充 material-ui datepicker 字段的值,我可以在控制台中看到日期对象正在正确创建,但它没有传递到状态,不知道我是什么做错了。
Here is the component这是组件
function DatePickerField(props) {
const { field , studentValues, control} = props;
const classes = useStyle();
const [date, setDate] = useState(null);
const handleChange = (date) => {
setDate(date)
}
// Check if the input name of the field we get from knack match the input name of the form and if yes display the value
useEffect(() => {
if (studentValues) {
const dataStudentArranged = DataStudent(studentValues);
dataStudentArranged.forEach((card) => {
card.cardValues.forEach((cardValue) => {
if (cardValue.formName === field.formName) {
const dateObject = fromUnixTime(cardValue.value/1000)
setDate(dateObject)
console.log('date object =>',dateObject)
}
})
})
}
}, []);
return (
<TableRow>
<TableCell>
<Controller defaultValue={date} name={field.formName} control = {control}
as = {
<DatePicker
className={classes.datePicker}
inputVariant = "outlined"
label={field.label}
value={date}
onChange={handleChange}
autoOk
variant="inline"
format= "dd, MMMM yyyy"
size="small"
/>
}
/>
</TableCell>
</TableRow>
)
}
export default DatePickerField
Thanks!谢谢!
The problem was with the react-hook-form, it was always passing the default values even after using useEfect, this question helped me to solve the issue: https://stackoverflow.com/a/62243132/9813493问题出在 react-hook-form 上,即使在使用 useEfect 之后它也总是传递默认值,这个问题帮助我解决了这个问题: https ://stackoverflow.com/a/62243132/9813493
Basicly when using react-hook-form with the control prop we should use the setValue function https://react-hook-form.com/api#setValue基本上,当使用 react-hook-form 和 control prop 时,我们应该使用 setValue 函数https://react-hook-form.com/api#setValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.