简体   繁体   中英

Using mapStateToProps and state with connect() in React

I am using Redux-Form & am trying to get the values from that form. The documentation suggests that the way to use getFormValues() is as such:

MyComponent = connect(
  state => ({
    values: getFormValues('myForm')(state),
  })
)(MyComponent)

In my component, I am currently using connect with mapStateToProps in my component. But how can I use both of these together? My current code (that doesn't work, as the personFormValues is undefined ), is as such:

export default reduxForm({
  form: 'personsForm'
})(connect(mapStateToProps, state => ({
  personFormValues: getFormValues('personsForm')(state)
}))(PersonsForm));

I have also tried:

export default reduxForm({
  form: 'personsForm'
})(connect(state => ({
  personFormValues: getFormValues('personsForm')(state),
  mapStateToProps
}))(PersonsForm));

and

export default reduxForm({
  form: 'personsForm'
})(connect(state => ({
  personFormValues: getFormValues('personsForm')(state),
}), mapStateToProps)(PersonsForm));

and

export default reduxForm({
  form: 'personsForm'
})(connect(state => ({
  personFormValues: getFormValues('personsForm')(state),
  personsForm: state.form.personsForm
}))(PersonsForm));

In the latter instance, personsForm and personFormValues returns as undefined.

What is the correct way to use both with connect ?

I got it working. I just added it into the mapStateToProps method like so:

const mapStateToProps = state => ({
  personsForm: state.form.personsForm,
  values: getFormValues('personsForm')(state)
});

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