我很困惑。当我尝试 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>
)
}
}
答案 0 :(得分:0)
要查看更新的状态,您可以将回调作为第二个参数传递给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)
}));
,您可以有条件地渲染组件,如下所示:
render() {
const { podcast} = this.state;
return (
<div>
{podcast.length &&
<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>
</h2> }
</div>
PS。确保您在API响应中获取数据并且Javascript是异步的。您的render方法将被调用,而无需等待API响应。一旦setState
到任何地方,您的组件都将重新呈现。它显示podcast
在第一次渲染时未定义
答案 1 :(得分:0)
当组件首次呈现时,this.state.podcast
为空,因此您尝试使用它的尝试将显示为未定义。 该组件在收到状态和其他道具的更新时会重新呈现。因此,当您的组件最初加载时,this.state.podcast
是不确定的,但是在收到播客时会重新呈现再次显示值。
答案 2 :(得分:0)
渲染触发时,您的播客列表为空。当数组为空时,Array.map
将有效地运行0个元素,这就是为什么它不会引发错误。
要console.log
,您可以首先使用console.log(this.state.podcast[0] && this.state.podcast[0].collectionId)
或简单地使用console.log(this.state.podcast[0])
检查第一个元素是否存在,如果定义的话,它将呈现整个对象。
答案 3 :(得分:0)