[英]Fetch data from API depending on the components props
我在解決如何根據我的PodcastList組件中的props.catergory值和設置狀態確定獲取數據的結構方面遇到問題
我可以在父組件(Home.js)中獲取數據,設置狀態並將狀態作為prop傳遞。 但是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
}
我會在podcastlist組件中執行此操作,如果您希望將數據返回到父組件,則可以運行回調,
將一個功能提供給podcastlist作為道具並像這樣運行該功能,
const podcasts =等待fetchPodcastCategory(this.props.categoryId); this.setState({podcasts,loading:false,},this.props.callback(podcasts))}
我認為您的設計並不算太糟糕。
基本上如果你改變
{category.map((pod) => {
同
{this.state.podcasts.map((pod) => {
此代碼應該工作。
您正試圖精確地完成什么?為什么該體系結構無法為您完成? 如果您澄清這一點,則可以獲得更好的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.