Reactjs:如何以react-redux形式获取子对象数据

时间:2017-04-06 11:30:27

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

API以下列方式提供数据(JSON格式):

[
  {
    "_id": 1,
    "name": "XYZ",
    "address": {
        "street": "",
        "pin_code": 69856,
        "country": "US",
        "city": "Boston"
     }
  }
]

如何从上述回复中获取address中的字段?我正在使用react-redux形式。

这是表单字段:

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class FetchUserForm extends Component {
 render() {
   const { fields: {name, street, country}, handleSubmit } = this.props;
   return(
    <form onSubmit={handleSubmit}>
      <div className='form-group'>
        <input type='text' className='form-control' placeholder='User Name' {...name}/>
      </div>

      <div className='form-group'>
        <input type='text' className='form-control' placeholder='Street' {...street}/>
      </div>
      <div className='form-group'>
        <input type='text' className='form-control' placeholder='country' {...country}/>
      </div>

      <button type='submit' className='btn btn-primary'> Update </button>
      <button type='reset' className='btn btn-default'> Cancel </button>
    </form>
  );
 }
}

export default reduxForm ({
  form: 'FetchUserForm',
  fields: ['name', 'street', 'country']
},null, { fetchUser })(FetchUserForm);

如图所示,我正在尝试从数据的子对象中获取街道和国家/地区。有人可以帮我获取表格中的实际数据。现在我得到null

1 个答案:

答案 0 :(得分:1)

您缺少显示使用此表单的代码/组件。但是,我猜测你的其他/同一个组件中的某个地方应该从initialize调用redux-form。既然,你还没有提供太多信息,我在这里假设一些事情,但总的来说这应该是这样的:

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';
import { connect } from 'react-redux';
import { initialize } from 'redux-form';

class SomeClass extends Component {
  constructor(props){
    super(props);
  }
  render() {
     const myInitialValues = {
       initialValues: {
          "name": this.props.user.name,
          "street": this.props.user.address.street, //note this
          "country": this.props.user.address.country //and this
       }
     }
    const { handleSubmit } = this.props;
       return(
           <FetchUserForm {...myInitialValues} onSubmit={this.someFunction.bind(this)}/>      
       );
   }
}

function mapStateToProps(state) {
  return{
    user:state.user
  }
}

export default connect(mapStateToProps,{someAction})(SomeClass);

检查我如何在initialValues对象中声明变量/字段名称。这就是通常可以做到的。希望你有一个全面的想法..