【问题标题】:How to access the redux store within the redux form如何在 redux 表单中访问 redux store
【发布时间】:2018-02-01 10:10:34
【问题描述】:

我是 react-redux 世界的新手,如果我遗漏了什么,请纠正我:

基本上我正在尝试通过 redux 存储访问主机名并在表单中使用它。截至目前,我只是在 redux 表单中使用主机名引用 window.location 但我想通过 redux 存储/通过任何其他更好的方法访问主机名,以便保持函数纯净?想法?

谢谢

编辑:

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)

问题:

如何将窗口对象存储在 redux 存储中,是否可以通过 redux 存储在 redux 表单中访问它们,或者是否会随时响应路由器帮助?

【问题讨论】:

  • 请添加您尝试的代码
  • 当然,刚刚添加 - 谢谢

标签: reactjs redux react-redux redux-form react-router-redux


【解决方案1】:

您应该将表单连接到 Redux 状态。

import { connect } from 'react-redux'

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

然后:

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

所以你可以通过 this.props.hostName 访问它,考虑到之前在 reducer 中设置了 hostName。

如果你使用React Router,你可以通过props访问history对象,它也有location属性。

【讨论】:

    【解决方案2】:

    不幸的是,前面提到的答案现在对我有用,

    这对我有用,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);
    

    我传递的“验证”是我的validation.js,因为我正在使用同步验证(如果有的话,它完全是可选的)

    'form' 是我在 reducer 中使用的状态名称。我的减速器代码,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多