reactjs - 是否可以在 Redux Form 的辅助函数中分配 initialValues?
问题描述
我已经阅读了如何以 redux 形式动态映射 initialValues,但我需要在类组件内的辅助函数中进行一些数据转换。我在辅助函数中执行此操作,因为我需要首先从 this.props.match.params 收集一些参数。这些参数有助于获取要以 redux 形式编辑的正确数据。提前致谢。我很感激任何帮助!
function mapStateToProps(state){
// First I tried to do the transformations here
// but I have no access to this.props.match.params
return {
data: state.data,
initialValues: {a: 'foo', b: 'faa'} //<== I believe I should insert initialValues here
}
}
这是我在创建表单之前收集必要数据的代码的一部分:
class Edit extends Component {
constructor(props){
super(props)
const path = this.props.match.params
this.state = {
file: path.file,
tree: path.tree,
branch: path.branch,
node: path.node,
row: path.row
}
}
componentWillMount(){
const {file} = this.state
if(!(file in this.props.data)){
this.props.getPageData('settings')
}else{
console.log('we have data')
}
}
doTransformations(){
let myData,dataToEdit
const {file,tree,branch,node} = this.state
myData = this.props.data[file]
if(myData){
// Data transformations
// Basically we want to create a nice object from the messy data coming from an XML FILE :-/
let dataToEdit = myData[file][tree][branch][node]
const arr = Object.entries(dataToEdit)
const myObj = {}
arr.map((i,x)=>{
myObj[i[0]] = i[1]._text
})
/// Somehow assign myObj to initialValues
}
}
解决方案
如果您需要从 mapStateToProps 中的组件访问道具,您可以使用 ownProps。
我能够这样:
function mapStateToProps(state,ownProps){
// Do the necessary transformations
const myData = state.data.settings
let dataToEdit, myObj = {}
if(myData){
// Get params
const {file,tree,branch,node} = ownProps.match.params
// Build path to data
dataToEdit = myData[file][tree][branch][node]
const arr = Object.entries(dataToEdit)
// We want to create a nice object from the messy data coming from an XML FILE :-/
arr.map((i)=>{
myObj[i[0]] = i[1]._text
})
}
// console.log(myObj)
return{
data: state.data,
initialValues: myObj
}
}
推荐阅读
- r - R中的ggmap:如何从地理编码中提取单个位置特征?
- database - 如何配置 pgadmin4 (PostgreSQL)
- ajax - Ajax 数据未发送到控制器函数 (CodeIgniter)
- javascript - 并行运行多个 Axios 请求以验证数据
- ios - 保持 NSUserActivity 向后兼容 Xcode 9
- sql - 如何从数据库中获取人的全名
- julia - Julia 中有类型减法运算吗?
- regex - 匹配序列化字符串
- angular - 如何在 BehaviorSubject 上链接订阅
? - python-3.x - 如何以 root 权限启动 anaconda-navigator ?(Linux)