Javascript React/Redux mapStateToProps与嵌套JSON
我有一个redux组件正在解析JSON(在底部),但我不知道如何获取嵌套的子对象。我认为我没有正确理解MapStateTops的工作原理 控制台日志正在转储子对象,但当我尝试访问services.name时Javascript React/Redux mapStateToProps与嵌套JSON,javascript,reactjs,redux,Javascript,Reactjs,Redux,我有一个redux组件正在解析JSON(在底部),但我不知道如何获取嵌套的子对象。我认为我没有正确理解MapStateTops的工作原理 控制台日志正在转储子对象,但当我尝试访问services.name时 “无法读取未定义的属性“name” 有人能帮我理解如何在这里映射属性吗?我在底部的API中提供了一个JSON示例 services-list.js import React, { Component } from 'react'; import { connect } from 'react
“无法读取未定义的属性“name”
有人能帮我理解如何在这里映射属性吗?我在底部的API中提供了一个JSON示例
services-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);
最后,我有一个公开axios的操作。点击这里:
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
};
}
我假设您认为
this.props.fetchServices()
将更新服务
减速机,然后将服务
作为道具通过MapStateTrops
传递如果这是正确的,请注意,您正在获取内部
组件willmount
,这是一个大的编号。引自: 避免在这种方法中引入任何副作用或订阅 您应该在
componentDidMount
中获取数据
此外,您可能认为在从ajax请求中获取数据之前不会调用render方法。您知道,react不会等待ajax调用返回数据,无论发生什么情况,render
方法都会被调用,因此第一个render
调用将尝试map
在服务的空数组上(我假设您的reducer中有一个空数组作为初始状态)。
然后您的renderServices
函数将得到一个空数组作为data
和data.services
实际上是未定义的
,因此当您尝试访问data.services.name
时,您会得到错误:
“无法读取未定义的属性'name'”
只需在渲染中使用一个条件:
<tbody>
{this.props.services && this.props.services.map(this.renderServices)}
</tbody>
yourconst name=data.services.name
应该是const name=data.name代码>即bcoz,您正在映射服务
,对于每个循环,您在renderServices
函数中得到一个服务
。正确,它只调用renderServices一次。我不明白的是如何在下一个对象没有命名的情况下映射它。好的,我更新了以componentDidMount发送获取,但同样的问题仍然存在。。。数据返回(我可以看到整个30条记录被记录),但我不知道如何映射,因为JSON只有一条顶级记录。问题是,我如何跳过顶部记录并映射子项。componentDidMount
不是解决方案,我只是提到了它,因为使用componentWillMount
这样做是不好的做法。我已经更新了我的答案,提供了更多的解释和一个有效的例子,我认为这应该会让你走上正确的道路。:)
<tbody>
{this.props.services && this.props.services.map(this.renderServices)}
</tbody>