我正在使用Vimeo API使用axios
和react
访问频道。我的代码设置正确,但是在编译后出现此错误:
TypeError:无法读取未定义的属性“ map”
关于这一行:{this.state.videos.map(video =>
这是完整的代码段供参考:
import React, { Component } from 'react';
import axios from 'axios';
class Apicall extends Component {
componentWillMount() {
this.getChannel();
}
getChannel() {
axios.get(`https://api.vimeo.com/channels/collegehumorbackstage/page:1`)
.then(res => {
const videos = res.data.data.children.map(obj => obj.data);
this.setState({videos});
});
}
constructor(props) {
super(props);
this.state = {
channel_id: 'collegehumorbackstage',
data: [],
per_page: '5',
paging: {
first: '/channels/collegehumorbackstage/videos?page=1',
last: '/channels/collegehumorbackstage/videos?page=2'
}
}
this.getChannel = this.getChannel.bind(this);
}
render() {
return (
<div className="container">
<ul>
{this.state.videos.map(video =>
<li key={video.uri}></li>
)}
</ul>
</div>
);
}
}
export default Apicall;
据我所知其他一切都很好,第二双眼睛总是有帮助的。我想念什么吗?
答案 0 :(得分:1)
那是因为最初您的状态中没有videos
。就是undefined
。
您应该为其提供默认值,例如一个空数组:
this.state = {
channel_id: 'collegehumorbackstage',
data: [],
per_page: '5',
paging: {
first: '/channels/collegehumorbackstage/videos?page=1',
last: '/channels/collegehumorbackstage/videos?page=2'
},
videos: [],
}