首页 > 解决方案 > 数组仅在我刷新页面时获取数据

问题描述

当我要去呈现我的类别组件的新路线(/category/name-of-category)时,我正在尝试的数组 console.log 是空的。但是当我刷新页面时,数组会获取数据吗?我究竟做错了什么?我不太擅长解释,所以我为它制作了一个视频。

问题视频:

在此处输入图像描述

这是我的类别组件,我在其中 console.log 数组:

import React, { Component } from 'react'
import PodcastList from './PodcastList'
import { podcastCategories } from './api'

export default class Category extends Component {

  render() {
    const categoryId = this.props.match.params.categoryId
    const categoryName = this.props.match.params.categoryName
    const currentCategory = podcastCategories.filter(category => category.slug === categoryName)
    console.log(currentCategory)
     return (
      <div className='container'>
        <PodcastList key={categoryId} categoryId={categoryId} name={categoryName} amount='100' />
      </div>
    )
  }
}

我的子组件:

import React, { Component } from 'react'
import PodcastItem from './PodcastItem'
import { Link } from 'react-router-dom'
import slugify from 'slugify'
import { fetchPodcastCategory } from './api'

export default class PodcastList extends Component {

  state = {
    podcasts: [],
    loading: true,
  }

  async componentDidMount () {
    const categoryId = this.props.categoryId
    const totalAmount = this.props.amount
    const podcasts = await fetchPodcastCategory(categoryId, totalAmount);
      this.setState({
        podcasts,
        loading: false,
      })
  }

  render() {
    const podcasts = this.state.podcasts
    const { name, amount, categoryId } = this.props

    let description;
            if (amount === '100') {
              description = (
                        <p>Populäraste poddarna inom {name}</p>
              )
            } else {
              description = (
                <p>Topp {amount} poddar inom {name} -&nbsp;
                <Link to={`/kategori/${slugify(name.toLowerCase())} `}>
                 Visa Topp 100
              </Link>
            </p>
              )
            }

      return (
         <div className='row category-list'>
            <div className='col-md-12'>
            <h2>{name}</h2>
            { description }
            {podcasts.map((pod) => {
                const podId = pod.id.attributes['im:id']
                const podImage300 = pod['im:image'][0].label.replace('55x55bb-85', '300x300bb-75')
                const podImage600 = pod['im:image'][1].label.replace('60x60bb-85', '600x600bb-75')
                const podImage900 = pod['im:image'][2].label.replace('170x170bb-85', '900x900bb-75')
                const podImages = { podImage300, podImage600, podImage900 }
                const podName = pod['im:name'].label
                return (
                    <div key={podId} className='pod-box'>
                    <PodcastItem id={podId} image={podImages} name={podName}/>
                    </div>
                )
            })}
            </div>
        </div>
      )
    }
}

我的 Api.js:

import Feed from 'feed-to-json-promise'

export async function fetchPodcastCategory (categoryId, amount) {
  const response = await fetch(`/api/podcast/${categoryId}/${amount}`);
  const podcasts = await response.json();

  return podcasts.feed.entry;
}

export async function fetchPodcast (podId) {
  const response = await fetch(`/api/podcast/${podId}`);
  const podcasts = await response.json();

  return podcasts.results;
}

export async function fetchPodcastEpisodes (feedUrl) {
  const feed = new Feed();
  const episodes = await feed.load(`/api/podcast/episodes?feedurl=${feedUrl}`)
  return episodes;
}


export const podcastCategories = [
  { id: '1301', name: 'Konst och kultur', slug: 'konst-och-kultur'},
  { id: '1303', name: 'Komedi och humor', slug: 'komedi-och-humor' },
  { id: '1304', name: 'Utbildning', slug: 'utbildning' },
  { id: '1305', name: 'Barn och familj', slug: 'barn-och-familj' },
  { id: '1307', name: 'Hälsa', slug: 'halsa' },
  { id: '1309', name: 'TV och Film', slug: 'tv-och-film' },
  { id: '1310', name: 'Musik', slug: 'musik' },
  { id: '1311', name: 'Nyheter och politik', slug: 'nyheter-och-politik' },
  { id: '1314', name: 'Religion och andlighet', slug: 'religion-och-andlighet' },
  { id: '1315', name: 'Vetenskap och medicin', slug: 'vetenskap-och-medicin' },
  { id: '1316', name: 'Sport och fritid', slug: 'sport-och-fritid' },
  { id: '1318', name: 'Tenik', slug: 'teknik' },
  { id: '1321', name: 'Affärer', slug: 'affarer' },
  { id: '1323', name: 'Spel och hobby', slug: 'spel-och-hobby' },
  { id: '1324', name: 'Samhälle och kultur', slug: 'samhalle-och-kultur' },
  { id: '1325', name: 'Myndighet och organisation', slug: 'myndighet-och-organisation' },
]

当我 console.log: podcastCategories&categoryName 在此处输入图像描述

标签: javascriptreactjsreact-router

解决方案


你能添加.api你带来的文件吗?

这是一个猜测......因为我看不到完整的图片,但似乎.api文件中没有正确输入。

你可以在控制台记录之前console.log(categoryName)吗?还有家长吗?如果是这样,请发布代码。console.log(podcastCategories)currentCategoryCategory

对不起。我会发表评论而不是回答,但我还没有足够的分数。:(


推荐阅读