Manage multiple redux form on page

孤街醉人 提交于 2020-06-17 13:21:30

问题


I have user data coming from back-end as an array of objects,

[{firstname: 'John', lastname: 'Doe'}, {firstname: 'Jane', lastname: 'Doe'}]

I am using a redux-form component to render these data.

tried to make the object keys dynamic by binding index to it, but then got unsure how to handle validation, data population etc.

Working code sample can be seen at,

https://codesandbox.io/s/determined-lake-ln25c

Now changing a field in on 1 form affects the other forms state. like after entering value in one field, all 'clear values' buttons get enabled.


回答1:


The problem is that all your forms are actually assigned the same name (form property value) when you call reduxForm. This property is treated as unique form identifier so that data for specific form can be get from store. According to docs:

form: string [required]

the name of your form and the key to where your form's state will be mounted under the redux-form reducer

Please note that although you generate unique formNumber using Math.random you're doing it only once in module file (please use console.log to see that formNumber is generated only once). So all instances of the UserForm component are assigned the same name at 'design time'. As a result when you then import form component and render it 3 times all instance use the same name. You can say that from redux-form point of view all these 3 form instances are actually the same single form and they use the same data from store.

According to redux-form docs all reduxForm config options

may be passed into reduxForm() at "design time" or passed in as props to your component at runtime.

So solution is to define unique form as a component prop at 'runtime' instead of in reduxForm config:

function App() {
  return (
    <div className="container">
      <h1 className="mb-3">Users</h1>
      <hr />
      {userData.map((user, idx) => {
        return <UserForm form={`form-${idx}`} key={`user_${idx}`} data={user} idx={idx} />;
      })}
    </div>
  );
}

And of course remove this value from reduxForm config:

export default reduxForm({
  validate
})(UserForm);
enter code here

This way all form instances are independent.

Since now all form instances are independent of each other you don't have to define field names this way: name={`firstName_${idx}`}. You can do it like this: name='firstName'



来源:https://stackoverflow.com/questions/57477076/manage-multiple-redux-form-on-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!