How to reset initial value in redux form

感情迁移 提交于 2019-12-23 06:51:39

问题


I'm using redux-form. I'm showing initial values in input fields from the state. When I click on reset, the input field is still showing initial values.

How can I reset the input field?

This is my code :

const mapStateToProps = (state) => {
    return {
        initialValues: {
            name:state.userInfo.data.name,
            email:state.userInfo.data.email,
            phone:state.userInfo.data.phone,
            city:state.userInfo.data.city.name,
        }
    };
}

This is how I'm calling initial value in the input field.

const renderField = ({ input, label, type, meta: { touched, error } }) => (
    <div>
        <input className="form-control control_new" {...input} placeholder={label} type={type}/>
    {touched && ((error && <span>{error}</span>))}
    </div>
)

<Field type="text" {...name} name="name" component={renderField} label="Enter Your Name" />

Thanks


回答1:


import {reset} from 'redux-form';

...

dispatch(reset('myForm'));  // requires form name



回答2:


Harsha's answer is correct, but you can also call this.props.reset(), which already knows your form name, from inside your decorated form component.

You can see it in action on the "Clear Values" button in the Simple Example.




回答3:


TLDR: set enableReinitialize: true on your form

I had this same problem recently and came across this post, with none of the answers working. Finally found the solution so hopefully this will help someone else. the problem is those initial values not getting reset when you reset the form. here is a github issue asking about it, and here is the current documentation about it




回答4:


Upon onClick of the clear button call a different function as follows.

onClick={this.onClearChanges}

Pass the initialValues to the function this way, and as everyone mentioned, Don't forget to set enableReinitialize: true.

onClearChanges = () => {
  const { reset, onClearChanges, InitialValues } = this.props;
  reset();
  onClearChanges(InitialValues);
};



回答5:


It's also possible to reset inside of your constructor if you don't have a button with a method to call.

I'm using a Drawer Navigator to navigate to different screens(not a clickable button with an onClick method) so I had to reset

constructor(props) {
  super(props);
  this.props.reset(); //<-- this
}

inside of the first component to handle that specific redux form and then I set

enableReinitialize: true 

for that form.



来源:https://stackoverflow.com/questions/42711504/how-to-reset-initial-value-in-redux-form

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