如何在 redux 表单中访问 redux 存储

2023-12-19

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

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

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)

问题:

如何将窗口对象存储在 redux 存储中,是否可以通过 redux 存储以 redux 形式访问它们,或者是否有可能对路由器帮助做出反应?


您应该将表单连接到 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。

如果您正在使用反应路由器 https://www.npmjs.com/package/react-router-dom,您可以访问history https://developer.mozilla.org/en-US/docs/Web/API/History_API通过 props 来获取对象,它也有 location 属性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 redux 表单中访问 redux 存储 的相关文章

随机推荐