首页 > 解决方案 > 是否可以在 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
    }
}

标签: reactjsreduxredux-form

解决方案


如果您需要从 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
}

}


推荐阅读