【问题标题】:Array only gets data when I refresh the page数组仅在我刷新页面时获取数据
【发布时间】:2019-03-07 08:28:06
【问题描述】:

当我要去呈现我的 Category 组件的新路由 (/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

【问题讨论】:

  • 什么意思?我的 componentDidMount() 在 PodcastList.js 中工作。但是在 Category.js 中,我只是想过滤一个数组和 console.log 我得到了什么?但这只有在我刷新页面时才有效?
  • 组件第一次渲染时可能prop categoryName 没有值?你能检查一下吗?
  • 我尝试了控制台日志 categoryName 并且得到了正确的值。

标签: javascript reactjs react-router


【解决方案1】:

我解决了!我真的认为这是一些模糊的事情。所以我尝试在终端中执行此操作:

  1. killall -9 node
  2. ps ax

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

【讨论】:

    【解决方案2】:

    Jonas,你的代码现在可以工作了,因为category.slug = categoryName 是一个赋值,而不是对真实性的检查。它将返回分配给category.slug 的值的真实性,即categoryName。所以似乎定义了categoryName,但并不严格等于category.slug。 Holly E 提出了一个很好的问题——你能在控制台中显示categoryName 显示的内容吗?那么podcastCategories 呢?如果您将其添加到上面的代码中,我们应该能够看到为什么严格相等没有达到预期的效果。

    【讨论】:

    • 你的权利.. 我的错。我现在用 console.log categoryName 和 podcastCategories @ZebGir 时得到的内容更新了这个问题
    【解决方案3】:

    我会检查categoryId,因为具有相同key&lt;PodcastList key={categoryId} 将被视为已安装并且仅使用新道具进行更新 - componentDidMount 不会被调用/解雇。

    【讨论】:

      【解决方案4】:

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

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

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

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

      【讨论】:

      • 我现在已将 .api 添加到我的问题中。不,类别没有父级。
      • 我可以 console.log 两个 categoryName 和 podcastCategories 并获取值。
      猜你喜欢
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      相关资源
      最近更新 更多