How to wire up redux-form bindings to the form's inputs

后端 未结 2 1638
天涯浪人
天涯浪人 2021-02-01 03:39

redux-form is a very compelling library for providing redux bindings for forms in a react application, which should be super-convenient. Unfortunately, using the library\'s own

相关标签:
2条回答
  • 2021-02-01 04:17

    connectReduxForm wraps your component with another component which handles passing in the fields and handleSubmit props, but you're blowing those away by passing them in yourself.

    Try this instead (renamed the prop to onSubmit):

    <ContactForm onSubmit={this.handleSubmit.bind(this)}/>
    

    And in ContactForm, pass your own submit handler to the handleSubmit function provided by redux-form:

    <form onSubmit={handleSubmit(this.props.onSubmit)}>
    

    I recommend using the React developer tools to get a better picture of what's going on - you'll see how redux-form wraps your component and passes it a whole bunch of props, as documented in its README.

    0 讨论(0)
  • 2021-02-01 04:21

    Thanks to Jonny Buchanan, who covered the most important point: don't do as I did and automatically assume that if props are required in your component, you must need to provide them yourself. The whole point of the higher-order function that is connectReduxForm is to provide them in the wrapper component. Fixing that immediately gave me event-handlers, for everything except Submit.

    The other critical oversight was here:

    NOTE – If you are not doing the connect()ing yourself (and it is recommended that you do not, unless you have an advanced use case that requires it), you must mount the reducer at form.

    I didn't catch the point of that. But, the implementation is here:

    import { createStore, combineReducers } from 'redux';
    import { reducer as formReducer } from 'redux-form';
    const reducers = {
      // ... your other reducers here ...
      form: formReducer           // <---- Mounted at 'form'
    }
    const reducer = combineReducers(reducers);
    const store = createStore(reducer);
    

    The formReducer can't be referenced at formReducer, but requires the syntax form: formReducer. This was the correction that properly enabled handleSubmit.

    0 讨论(0)
提交回复
热议问题