英文:
How react-hook-form prevents rerender when formState is not declared
问题
I'm watching a react-hook-form tutorial. They show an example at https://youtu.be/RkXv4AXXC_4?t=170
let renderCount = 0;
const App = () => {
const {register, handleSubmit, /*formState: {errors}*/} = useForm();
renderCount++;
//...
}
https://codesandbox.io/s/react-hook-form-magic-1-pcxdhh?file=/src/App.js
If you submit a form that has validation errors without declaring formState: {errors}
above, the component won't rerender.
But if you declare formState: {errors}
above, the component will rerender when you submit with errors.
What is the mechanism that is used to prevent rerender in the first case, and do it in the second case?
英文:
I'm watching a react-hook-form tutorial. They show an example at https://youtu.be/RkXv4AXXC_4?t=170
let renderCount = 0;
const App = () => {
const {register, handleSubmit, /*formState: {errors}*/} = useForm();
renderCount++;
//...
}
https://codesandbox.io/s/react-hook-form-magic-1-pcxdhh?file=/src/App.js
If you submit a form that has validation errors without declaring formState: {errors}
above, the component won't rerender.
But if you declare formState: {errors}
above, the component will rerender when you submit with errors.
What is the mechanism that is used to prevent rerender in the first case, and do it in the second case?
答案1
得分: 1
formState
是一个 Proxy
。如果你从中访问任何内容,它会订阅该属性,并在该属性的值发生变化时重新渲染组件。
例如:如果你访问 isValid
属性,当满足以下条件时组件将重新渲染:
- 两个输入都为空,因为它们是必填的,所以
isValid
将为假 - 两个输入都有值,
isValid
将为真
英文:
The formState
is a Proxy
. If you access anything from it, it subscribes to that property and re-renders the component when that property changes its value
For example: If you access the isValid
property, the component will re-render if:
- both inputs are empty, since they are required, isValid will be false
- both inputs have value, isValid will be true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论