根据props.catergory组件中的PodcastList值和设置状态,找出如何设置到获取数据的结构存在问题
我可以在父组件(Home.js)中获取数据,设置状态并将状态作为支持传递。但是API端点需要接受一个categoryId,我不能一次获取所有的播客。这就是为什么我制作了一个包含和categoryId的子组件。如下所示:
<PodcastList category='1301' />
我的任务是在子组件中进行提取,将this.props.category传递给api端点。(我不知道自己在做什么)
有人能帮我解释一下如何完成我想要的吗?
我的代码如下所示:
Home.js组件:
import React, { Component } from 'react'
import { fetchPopularPodcasts } from './api'
import PodcastList from './PodcastList'
export default class Home extends Component {
render() {
return (
<div className='container'>
<PodcastList category='1301' /> // Lists all Podcasts from category: Arts
<PodcastList category='1303' /> // Lists all Podcasts from category: Comedy
<PodcastList category='1304' /> // Lists all Podcasts from category: Educationrts
<PodcastList category='1305' /> // Lists all Podcasts from category: Kids & Family
</div>
);
}PodcastList.js组件
import React from 'react'
import { fetchPodcastCategory } from './api'
export default class PodcastList extends Component {
state = {
podcasts: [],
loading: true,
}
async componentDidMount () {
const podcasts = await fetchPodcastCategory(this.props.categoryId);
this.setState({
podcasts,
loading: false,
})
}
render() {
return (
<div className='row'>
<div className='col-md-12'>
{category.map((pod) => {
return (
<div className='pod-box'>
{pod.Title}
{pod.Label}
</div>
)
})}
</div>
</div>
)
}
}
export default PodcastList;Api.js
import Feed from 'feed-to-json-promise'
export async function fetchPopularPodcasts () {
const response = await fetch('https://itunes.apple.com/search?term=podcast&country=se&media=podcast&entity=podcast&limit=200')
const podcasts = await response.json()
return podcasts.results
}
export async function fetchPodcastCategory (categoryId) {
const response = await fetch(`https://itunes.apple.com/se/rss/toppodcasts/limit=100/genre=${categoryId}/explicit=true/json`)
const podcasts = await response.json()
return podcasts.feed
}
export async function fetchPodcast (podId) {
const response = await fetch(`https://itunes.apple.com/lookup?id=${podId}&country=se`)
const podcasts = await response.json()
return podcasts.results
}
export async function fetchPodcastEpisodes (feedUrl) {
const feed = new Feed()
const episodes = await feed.load(feedUrl)
return episodes
}发布于 2018-09-26 09:05:28
我会在podcastlist组件中这样做,如果您想将数据返回到父组件,您可以运行回调,
给podcastlist一个函数作为支柱然后像这样运行这个函数,
const =等待fetchPodcastCategory(this.props.categoryId);this.setState({ podcast,loading: false,},this.props.callback(Podcast))}
发布于 2018-09-26 09:45:02
我不认为你的设计很糟糕。
基本上如果你改变了
{category.map((pod) => {使用
{this.state.podcasts.map((pod) => {这段代码应该能用。
你到底想要完成什么,为什么这个体系结构不适合你呢?如果你澄清这一点,你可以得到一个更好的答案。
https://stackoverflow.com/questions/52513811
复制相似问题