How to get Redux Form data in another Component

2020-02-01 07:59发布

问题:

How can i pass the data from redux form, So that i can access that data in App.js? here is the code i have written using redux-form.after i click on submit the data should be passed from form.js to app.js. and the data should be displayed on page.

here is form.js-

const Form=({fields:{name,address}})=>(
  <form>
    <center>
    <div>
      <label>First Name</label>
      <Field type="text" component="input" placeholder="Name" name="name"/>
    </div>
    <div>
      <label>Address</label>
      <Field type="text" component="input" placeholder="Phone" name="phone" />
    </div>
    <button type="submit">Submit</button>
  </center>
  </form>
)


export default reduxForm({
  form: 'form',
  fields: ['name', 'address']
})(Form);

how can i pass this inputed data to app.js?

回答1:

What you need to do is use getFormValues to get the redux field values

So in App.js you can have

import {getFormValues} from 'redux-form';

..
const App = (props) => {
      var {name, phone} = props.formStates
      console.log(name, phone);
}

function mapStateToProps(state) {
    return {
         formStates: getFormValues('form')(state) // here 'form' is the name you have given your redux form 
    }
}

export default connect(mapStateToProps)(App)


回答2:

The above mentioned answer is absolutely correct however, when your form component gets unmounted the state may get destroyed and then it will not be available in any other component.To fix this you can add destroyOnUnmount: false to your reduxForm wrapper like this

export default reduxForm({
  form: 'form',
  destroyOnUnmount: false, 
})(Form)

Now you can get the form data in any component by following the above answer. Hope this helps