数组仅在刷新页面时获取数据

时间:2018-10-02 08:17:12

标签: javascript reactjs react-router

当我转到呈现我的Category组件的新路由(/ category / category-category)时,我正在尝试的数组console.log为空。但是,当我刷新页面时,数组会获取数据吗?我究竟做错了什么?我不太善于解释,所以我为此制作了一个视频。

问题视频:

enter image description here

这是我的“类别组件”,我在其中控制台记录阵列:

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时:podcastCategoriescategoryName enter image description here

4 个答案:

答案 0 :(得分:0)

可以添加要引入的.api文件吗?

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

在控制台日志记录console.log(categoryName)之前,您可以console.log(podcastCategories)currentCategory吗?还有Category的父母吗?如果是这样,请发布该代码。

对不起。我要评论而不是回答,但我的观点还不够。 :(

答案 1 :(得分:0)

我会检查const frame = getFrameById("my-frame-id"); const page = frame.currentPage; let ico = page.getViewById("ico4"); ,因为具有相同categoryId的{​​{1}}将被视为已经安装,并且仅使用新道具进行更新-<PodcastList key={categoryId}将不会被调用/被解雇。

答案 2 :(得分:0)

我解决了!我真的很难理解这是模糊的。因此,我尝试在终端中执行此操作:

  1. killall -9 node
  2. ps ax

,然后重启我的node.js服务器。出于某种原因,它现在可以工作了。

答案 3 :(得分:0)

乔纳斯(Jonas),您的代码现在可以使用了,因为category.slug = categoryName是一项分配,而不是事实核对。它将返回分配给category.slug的值,即categoryName的真实性。因此似乎categoryName已定义,但并不严格等于category.slug。 Holly E问了一个好问题-您可以显示控制台中的categoryName内容吗?那podcastCategories又如何呢?如果您将其添加到上面的代码中,我们应该能够看到为什么严格的平等并没有达到预期的效果。