简体   繁体   English

使用 FormProvider 时如何访问 formState.errors

[英]How to access formState.errors when using FormProvider

I'm building an abstract "deeply-nested" form component that uses FormProvider .我正在构建一个使用FormProvider的抽象“深度嵌套”表单组件。 I have error validation working at the field level, but I can't figure out how to access the errors object at the formState level.我在field级别进行了错误验证,但我不知道如何在formState级别访问errors object。

The FormProvider docs say that "FormProvider requires all useForm methods," and the example code goes FormProvider文档说“FormProvider 需要所有 useForm 方法”,示例代码如下

export default function App() {
  const methods = useForm();
  const onSubmit = data => console.log(data);

  return (
    <FormProvider {...methods} > // pass all methods into the context
    ...

My (seemingly working) abstract form component looks like this:我的(看似有效的)抽象表单组件如下所示:

let renderCount = 0;

function FormDialog(props) {
  const {
    open, onClose, loading, headline, noEscape, onFormSubmit, content, actions
  } = props;

  renderCount++;

  let validationSchema = YupObject().shape({});

  // construct schema
  content.forEach(item => {
    validationSchema = validationSchema.concat(YupObject().shape({
      [item.component.props.name]: item.validation
    }));
  });

  const methods = useForm({
    resolver: yupResolver(validationSchema)
  });

  return (
    <Dialog
      open={open}
      onClose={onClose}
      disableEscapeKeyDown={loading || noEscape}
    >
      <DialogTitle>{headline}</DialogTitle>
      <Box>
        Render Count: {renderCount}
      </Box>
      <FormProvider {...methods}>
        <DialogContent>
          <Box component="form" 
            sx={{
              onSubmit: methods.handleSubmit(onFormSubmit)
            }}
          >
            <FormContent content={content} />
          </Box>
          <HighlightedInformation>
          </HighlightedInformation>
        </DialogContent>
        <DialogActions>
          <FormActions actions={actions} />
        </DialogActions>
      </FormProvider>
    </Dialog>
  );
}

export default FormDialog;

Like that, it renders, displays "Render Count: 2" (because I'm in dev mode, therefore using React.StrictMode ) and nicely points out errors at the field level.就像那样,它渲染,显示“渲染计数:2”(因为我处于开发模式,因此使用React.StrictMode )并很好地指出了field级别的错误。 However, I can't figure out how to access the formState errors property.但是,我不知道如何访问formState errors属性。

All of the examples I can find pull the formState out during the initial useForm call:在最初的useForm调用期间,我能找到的所有示例都将formState拉出:

  const {
    register,
    handleSubmit,
    formState
  } = useForm();

However, I need to pull all of the methods out because of the FormProvider .但是,由于FormProvider ,我需要提取所有methods It doesn't seem a good idea to explicitly restructure them all.明确地重组它们似乎不是一个好主意。 Various things I've tried:我尝试过的各种事情:

useFormState():使用表单状态():

  ...
  const methods = useForm({
    resolver: yupResolver(validationSchema)
  });
  
  const { errors } = useFormState();
  console.log('errors', errors);
  ...

explicitly pass control显式传递control

  const { errors } = useFormState( methods.control );
  console.log('errors', errors);

both result in TypeError: null is not an object (evaluating 'methods.control') .两者都导致TypeError: null is not an object (evaluating 'methods.control')

Destructure methods to get to the object :获取 object 的解构methods

  const methods = useForm({
    resolver: yupResolver(validationSchema)
  });

  const { formState: {errors} } = methods;
  console.log('errors', errors);

Wrap in useEffect as described in the formState docs :按照formState文档中的描述包装useEffect :

  useEffect(() => {
    console.log('errors:', methods.formState.errors);
  },[methods.formState]);

Both of the latter two result in infinite re-renders and the browser hanging.后两者都导致无限重新渲染和浏览器挂起。

So, how do I get to formState errors when using FormProvider and pulling out all of the methods ?那么,在使用FormProvider并拉出所有methods时,如何处理formState errors

I've changed a few things and it seems to work now: Codesandbox我改变了一些东西,现在似乎可以工作了: Codesandbox

  1. Don't pass onSubmit as sx prop.不要将onSubmit作为sx道具传递。 I think sx is supposed to only accept style props, not sure why it allows callbacks and etc.我认为 sx 应该只接受样式道具,不知道为什么它允许回调等。

  2. Wrap form element around submit button, otherwise you won't be able to submit it.form元素包裹在提交按钮周围,否则您将无法提交。

  3. ConnectForm was doing nothing so I removed it too, but not sure if it has any effect on the bug. ConnectForm什么也没做,所以我也删除了它,但不确定它是否对 bug 有任何影响。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 react-hook-form 的 formstate.errors 开玩笑测试中的奇怪行为 - react-hook-form's formstate.errors weird behavior in jest test react-hook-form FormProvider 在从内部组件库使用时不起作用 - react-hook-form FormProvider not working when using it from internal component library 如何使用 React-Final-Form 在 handleSubmit 函数中正确获取 FormState(dirtyFields、prestine 等) - How to get propperly FormState (dirtyFields, prestine, etc.) in handleSubmit function using React-Final-Form 如何在react-final-form中恢复formState - How to restore formState in react-final-form react-hook-form FormProvider 与受控组件的性能(或者,如何记忆受控组件) - react-hook-form FormProvider performance with controlled components (or, how to memoize controlled components) 使用 React 时如何查看 PHP 错误? - How to view PHP errors when using React? 我使用 react-hook-form 时出错; TypeError:无法读取 null 的属性(读取“formState”) - I've got an error using react-hook-form; TypeError: Cannot read properties of null (reading 'formState') 使用browserify和reactify时如何处理react错误? - How to handle react errors when using browserify and reactify? 使用 React refs 时如何解决这些 TypeScript 错误? - How to resolve these TypeScript errors when using React refs? react-hook-form - 如何在提交表单后重置 formState.isDirty - react-hook-form - how to reset formState.isDirty after form submitting
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM