我有一个解析 JSON 的 redux 组件(在底部),但我不知道如何获取嵌套的子对象。我认为我没有正确理解 mapStateToProps 的工作原理。
控制台日志正在转储子对象,但是当我尝试访问 services.name 时,我得到
"Cannot read property 'name' of undefined"
有人可以帮助我了解如何在此处映射属性吗?我在底部包含了一个我从 API 中获取的 JSON 示例。
服务-list.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
class ServicesList extends Component {
componentDidMount(){
this.props.fetchServices();
}
render() {
//console.log('render called in ServicesList component');
return (
<table className='table table-hover'>
<thead>
<tr>
<th>Service Name</th>
</tr>
</thead>
<tbody>
{this.props.services.map(this.renderServices)}
</tbody>
</table>
);
}
renderServices(data) {
console.log(data.services);
const name = data.services.name;
return(
<tr key={name}>
<td>{name}</td>
</tr>
);
}
}
function mapStateToProps({services}) {
return { services };
}
export default connect(mapStateToProps, actions)(ServicesList);
我的 JSON 如下所示:
{
"services": [
{
"name": "redemption-service",
"versions": {
"desired": "20170922_145033",
"deployed": "20170922_145033"
},
"version": "20170922_145033"
}, {
"name": "client-service",
"versions": {
"desired": "20170608_094954",
"deployed": "20170608_094954"
},
"version": "20170608_094954"
}, {
"name": "content-rules-service",
"versions": {
"desired": "20170922_130454",
"deployed": "20170922_130454"
},
"version": "20170922_130454"
}
]
}
最后,我有一个在这里公开 axios.get 的操作:
import axios from 'axios';
const ROOT_URL=`http://localhost:8080/services.json`;
export const FETCH_SERVICES = 'FETCH_SERVICES';
export function fetchServices(){
const url = `${ROOT_URL}`;
const request = axios.get(url);
return{
type: FETCH_SERVICES,
payload: request
};
}