【问题标题】:Reactjs: How to fetch child object data in react-redux formReactjs:如何以 react-redux 形式获取子对象数据
【发布时间】:2017-04-06 11:30:27
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    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);
    

    检查我如何在initialValuesobject 中声明变量/字段名称。这就是通常可以做到的方式。希望你有一个整体的想法..

    【讨论】:

      猜你喜欢
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2019-12-24
      • 2018-05-28
      • 1970-01-01
      • 2021-07-23
      相关资源
      最近更新 更多