我很困惑..当我尝试console.log(this.state.podcast [0] .collectionId)我得到一个错误说:TypeError:无法读取未定义的属性'collectionId'。
但!如果我删除console.log,那么一切正常..
我正在学习React JS的学习过程中。有人能指出正确的方向吗?
这是我的组成部分:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Podcast extends Component {
constructor(props) {
super(props);
this.state = {
podcast: []
};
}
// Fetches podID from props.match
fetchPodcast () {
const podcastID = this.props.match.params.podID
fetch(`https://itunes.apple.com/lookup?id=${podcastID}`)
.then(response => response.json())
.then(data => this.setState({
podcast: data.results
}));
}
componentDidMount () {
this.fetchPodcast()
}
render() {
console.log(this.state.podcast[0].collectionId)
return (
<div>
<h2> {this.props.match.params.podID}</h2>
<ul>
{this.state.podcast.map(podcast =>
<li key={podcast.collectionId}>
<Link to={`/podcast/${podcast.collectionId}`}>{podcast.collectionName}</Link>
</li>
)}
</ul>
</div>
)
}
}
当您的组件首次渲染时,您的componentDidMount
为空,因此您尝试使用它将显示为未定义。当组件收到状态和其他道具的更新时,该组件会重新呈现。因此,当您的组件最初加载时,this.state.podcast
未定义,但是当它收到播客时,它会再次重新渲染,显示值。
渲染触发时,您的播客列表为空。当数组为空时,render
将有效地运行0个元素,这就是为什么它不会抛出错误。对this.state.podcast
来说,你可以先用this.state.podcast
检查第一个元素是否存在,或者简单地用Array.map
来检查整个对象是否已定义。
要查看更新的状态,您可以将回调传递给console.log
作为第二个参数:
console.log(this.state.podcast[0] && this.state.podcast[0].collectionId)
并且您可以有条件地渲染您的组件,如下所示:
console.log(this.state.podcast[0])
PS。确保您在API响应中获取数据并且Javascript是异步的。您将在不等待API响应的情况下调用render方法。一旦你setState
你的组件将被重新渲染。它首次渲染时将fetch(`https://itunes.apple.com/lookup?id=${podcastID}`)
.then(response => response.json())
.then(data => this.setState({
podcast: data.results
},()=>{
console.log(this.state.podcast)
}));
显示为undefined