How to access the redux store within the redux form

Deadly 提交于 2019-12-11 03:28:10

问题


I'm a newbie to the react-redux world, please correct me if I'm missing something:

Basically I'm trying to access the hostname via redux store and use it inside the form. As of now I'm just using the hostname reference window.location within the redux form but I would like to access the hostname via the redux store/ via any other better approach so I can keep the function pure? Thoughts?

Thanks

Edit:

import React from 'react'
import { Field, reduxForm } from 'redux-form'

const SimpleForm = (props) => {
const { handleSubmit, pristine, reset, submitting } = props
// goal is to prevent this here and do it via redux store or 
// any other options
// so I can avoid external calls inside pure function
const hostName = window.location.hostname;

return (
<form onSubmit={handleSubmit}>
  <div>
    <label>First Name</label>
    <div>
      <Field name="firstName" component="input" type="text" placeholder="First Name"/>
    </div>
  </div>
</form>
 )
 }

export default reduxForm({
 form: 'simple'  // a unique identifier for this form
})(SimpleForm)

Question:

How can I store the window objects in the redux store and is it possible to access them in the redux forms via redux store or would react router help by any chance?


回答1:


You should connect your form to the Redux state.

import { connect } from 'react-redux'

export default reduxForm({
 form: 'simple'  // a unique identifier for this form
})(connect(mapStateToProps)(SimpleForm)

and then:

const mapStateToProps = state => {
  return {
    hostName: state.reducerName.hostName
  }
}

so you can access it through this.props.hostName, considering that hostName is set in the reducer previously.

If you are using React Router, you can access the history object through props, which also has the location property.




回答2:


The previously mentioned answer did now work for me sadly,

Here is what worked for me, reference to react-redux doc

import { connect } from 'react-redux';

const mapStateToProps = state => {
  return {
    form: state.form
  }
}

ClassName= connect(
   mapStateToProps,
   mapDispatchToProps
)(ClassName);

export default reduxForm({
  form: 'ObjectRepo',
  validate: validateObjects
})(ClassName);

The 'validate' that im passing is my validation.js, since i am using sync validations (if you have any, its completely optional)

'form' is the name of state i have used in my reducer. My reducer code,

const allReducers = combineReducers({
  form: reduxFormReducer
});


来源:https://stackoverflow.com/questions/45846162/how-to-access-the-redux-store-within-the-redux-form

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