如何在 redux 表单中访问 redux store [英] How to access the redux store within the redux form
问题描述
我是 react-redux 世界的新手,如果我遗漏了什么,请纠正我:
基本上我试图通过 redux 存储访问主机名并在表单中使用它.到目前为止,我只是在 redux 表单中使用主机名引用 window.location 但我想通过 redux store/通过任何其他更好的方法访问主机名,以便我可以保持函数的纯净?想法?
谢谢
从 'react' 导入 Reactimport { Field, reduxForm } from 'redux-form'const SimpleForm = (props) =>{const { handleSubmit, 原始, 重置, 提交 } = props//目标是在这里防止这种情况并通过 redux store 或//任何其他选项//这样我就可以避免纯函数内部的外部调用const hostName = window.location.hostname;返回 (<form onSubmit={handleSubmit}><div><label>名字</label><div><Field name="firstName" component="input" type="text" placeholder="First Name"/>
</表单>)}导出默认 reduxForm({form: 'simple'//此表单的唯一标识符})(简单的模式)
问题:
如何将窗口对象存储在 redux 存储中,是否可以通过 redux 存储在 redux 表单中访问它们,或者是否可以随时响应路由器帮助?
您应该将表单连接到 Redux 状态.
import { connect } from 'react-redux'导出默认 reduxForm({form: 'simple'//此表单的唯一标识符})(connect(mapStateToProps)(SimpleForm)
然后:
const mapStateToProps = state =>{返回 {主机名:state.reducerName.hostName}}
所以你可以通过this.props.hostName访问它,考虑到hostName之前是在reducer中设置的.
如果您使用 React Router,您可以访问 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: 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? You should connect your form to the Redux state. and then: 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. 这篇关于如何在 redux 表单中访问 redux store的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!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)
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
}
}