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
答案 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
对象中声明变量/字段名称。这就是通常可以做到的。希望你有一个全面的想法..