react-hook-form 在 formState 未声明时如何防止重新渲染

huangapple go评论86阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月22日 20:32:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定