简体   繁体   中英

Redux - How to get form values in its submit handler and call event.preventDefault()?

What I've been trying is to pass values from a form with Redux-Form to its handleSubmit with event.preventDefault(), so that submitting this form won't change URL.

Chances are that this is to do with react-router .

Here are excerpts of my attempt...

//form
class SampleForm extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {      
        return (
          <div>
            <form onSubmit={this.props.handleSubmit}>                   
                <Field name="body" component="textarea" />
                <button type="submit" className="btn">Save</button>
            </form>
          </div>
        );
    }
}

//container...
class Container extends React.Component {
    handleSubmit(event) {        
        event.preventDefault();
        //How can I get the values from SampleForm?
    }

    render() {
        return (
            <div>
                <SampleForm handleSubmit={this.handleSubmit}/>
            </div>
        );
    }
}

I'm using react-router . Because of this, when I submit the form, the URL gets updated with the submitted values.

(When I was NOT using react-router , this didn't happen - I could simply get the values from handleSubmit() .)

Any advice will be appreciated.

So you have your SampleForm component wrapped with Redux-Form. This decorated component should be passed an onSubmit prop from your Container which is the handler. You are passing handleSubmit() as a prop which is conflicting with redux-form's handleSubmit "middleware" that it is trying to do for you.

Change your Container component to pass "onSubmit" in in place of "handleSubmit" as follows:

//container...
class Container extends React.Component {
    handleSubmit(event) {        
        event.preventDefault();
        //How can I get the values from SampleForm?
    }

    render() {
        return (
            <div>
                <SampleForm onSubmit={this.handleSubmit}/>
            </div>
        );
    }
}

Now, your Container component should correctly receive the argument "values" as an argument and should be an object of form fields key/values. There is no need to call event.preventDefault() because redux-form's middleware (as I mentioned earlier) does that for you.

So instead of handleSubmit(event), change the event argument to "values" as below:

handleSubmit(values) {        
    console.log(values);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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