我试图制作一个类似const feedURL = this.state.podcasts[0].feedUrl
的const,但是状态并没有按照我在上面设置播客状态时所做的获取操作进行更新,因此我了解到TypeError: Cannot read property 'feedUrl' of undefined
。
但是我应该如何使它工作?谁能指出我正确的方向。
这是我的组件:
import React, { Component } from 'react'
import Feed from 'feed-to-json-promise'
import sanitizeHtml from 'sanitize-html'
export default class Podcast extends Component {
state = {
podcasts: [],
episodes: [],
loading: true,
}
componentDidMount () {
const podId = this.props.match.params.podId
fetch(`https://itunes.apple.com/lookup?id=${podId}`)
.then(response => response.json())
.then(podcasts => this.setState({
podcasts: podcasts.results,
loading: false,
}))
const feed = new Feed()
const feedURL = this.state.podcasts[0].feedUrl
feed.load(feedURL)
.then(feedInfo => this.setState({
episodes: feedInfo.items
}))
}
render() {
const { podcasts, episodes, loading } = this.state
const { podId } = this.props.match.params
if (loading === true) return null
const { collectionName, artworkUrl600, primaryGenreName, feedUrl } = podcasts.find((podcast) => podcast.collectionId === Number(podId))
return (
<div>
<img src={artworkUrl600} alt={collectionName} style={{width: '300px'}} />
<h2>{collectionName} ({podId})</h2>
<p>{primaryGenreName}</p>
<p><a href={feedUrl} target='_blank'>RSS Feed URL</a></p>
<ul>
{episodes.map((episode, i) => {
const { title, description } = episode;
return (
<li key={title.slice(0, 3)}>
<h2>{title}</h2>
<p>{sanitizeHtml(description, {allowedTags: [], allowedAttributes: []})}</p>
</li>
)
})}
</ul>
</div>
)
}
}