简体   繁体   English

如何在react-final-form中更改onSubmit的表单值?

[英]How to change form values onSubmit in react-final-form?

I'm using React-Admin , which uses react-final-form as it's underlying component for the forms it uses.我正在使用React-Admin ,它使用react-final-form作为它使用的表单的基础组件。

I'm trying to make a REST call on submit with only the fields that have been changed.我试图在提交时仅使用已更改的字段进行 REST 调用。 So, given Field A and Field B are different resources that are to be sent to different REST routes, given that both are in the form, and that only Field B has been changed, then only Field B should be sent to the backend, so as to prevent redundant multiple API requests.因此,鉴于字段 A 和字段 B 是要发送到不同 REST 路由的不同资源,鉴于两者都在表单中,并且只有字段 B 已更改,则应仅将字段 B 发送到后端,因此以防止冗余的多个 API 请求。

Anyway, I took a look here , and the problem that I'm running into is the following:无论如何,我看了一下here ,我遇到的问题如下:

I have this onSubmit handler:我有这个 onSubmit 处理程序:

  const handleClick = useCallback(() => {
    // prints 'before' value
    console.log(JSON.parse(JSON.stringify(form.getState().values)));

    const values = form.getState().values;

    // take out Field A, because Field A is NOT to be sent in the request
    const { FieldA, ...valuesToSubmit } = values;

    // How can I do this part? <------
    form.change('values', valuesToSubmit);

    handleSubmitWithRedirect(redirect);
  }, [form]); // useForm hook for react-final-form

I managed to change individual field values by doing something like,我设法通过执行以下操作来更改各个字段值,

form.change('FieldB', 'test');

But if I have many fields, I do not want to change all of them individually.但是如果我有很多字段,我不想单独更改所有字段。 Is it possible to replace the whole values object with form.change(...) ?是否可以用form.change(...)替换整个values对象?

To anyone being faced with this issue in the future, I managed to delete the fields that are not to be submitted to their respective backend REST route by tracking the values that have not changed and then setting their value to undefined upon submit.对于将来遇到此问题的任何人,我通过跟踪未更改的值,然后在提交时将其值设置为undefined ,设法删除了不会提交到各自后端 REST 路由的字段。 Something like this, (note, this is in conjunction with the React-Admin framework, but I believe it'd work regardless of where you're using react-final-form.像这样的东西,(注意,这与 React-Admin 框架结合使用,但我相信无论您在何处使用 react-final-form,它都可以工作。

. . .
const { handleSubmitWithRedirect, redirect } = props;

const handleClick = useCallback(() => {
  // The field that I don't want sent to the backend
  form.change('fieldA', undefined);

  handleSubmitWithRedirect(redirect);
}, [form]);

. . .

return (
  . . .
  <SaveButton
    handleSubmitWithRedirect={handleClick}
  />
  . . .
)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM