使用console.log时,状态未定义

问题描述 投票:0回答:4

我很困惑..当我尝试console.log(this.state.podcast [0] .collectionId)我得到一个错误说:TypeError:无法读取未定义的属性'collectionId'。

但!如果我删除console.log,那么一切正常..

我正在学习React JS的学习过程中。有人能指出正确的方向吗?

这是我的组成部分:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

export default class Podcast extends Component {

  constructor(props) {
    super(props); 
    this.state = {
      podcast: []
    };
  }

  // Fetches podID from props.match
  fetchPodcast () {
    const podcastID = this.props.match.params.podID

    fetch(`https://itunes.apple.com/lookup?id=${podcastID}`)
      .then(response => response.json())
      .then(data => this.setState({
        podcast: data.results
      }));
  }

  componentDidMount () {
    this.fetchPodcast()
  }

  render() {
    console.log(this.state.podcast[0].collectionId)
    return (
      <div>
          <h2> {this.props.match.params.podID}</h2>
          <ul>
          {this.state.podcast.map(podcast =>
              <li key={podcast.collectionId}>
              <Link to={`/podcast/${podcast.collectionId}`}>{podcast.collectionName}</Link>
              </li>
          )}
          </ul>


</div>
)
  }
}
reactjs
4个回答
0
投票

React Lifecycle methods

上图将让您对React的工作原理有所了解,检查render阶段何时发生。

因此,如果我们将此与您的情况相关联,则在调用构造函数调用render()之后,由于this.state.podcast是一个空数组,因此当您尝试访问非现有索引值时,console.log会抛出错误。 map函数也没有执行,因为this.state.podcast是一个空数组。

现在在qazxsw poi之后,qazxsw poi获得价值,qazxsw poi再次被召唤,你可以看到收藏细节。


0
投票

当您的组件首次渲染时,您的componentDidMount为空,因此您尝试使用它将显示为未定义。当组件收到状态和其他道具的更新时,该组件会重新呈现。因此,当您的组件最初加载时,this.state.podcast未定义,但是当它收到播客时,它会再次重新渲染,显示值。


0
投票

渲染触发时,您的播客列表为空。当数组为空时,render将有效地运行0个元素,这就是为什么它不会抛出错误。对this.state.podcast来说,你可以先用this.state.podcast检查第一个元素是否存在,或者简单地用Array.map来检查整个对象是否已定义。


0
投票

要查看更新的状态,您可以将回调传递给console.log作为第二个参数:

console.log(this.state.podcast[0] && this.state.podcast[0].collectionId)

并且您可以有条件地渲染您的组件,如下所示:

console.log(this.state.podcast[0])

PS。确保您在API响应中获取数据并且Javascript是异步的。您将在不等待API响应的情况下调用render方法。一旦你setState你的组件将被重新渲染。它首次渲染时将fetch(`https://itunes.apple.com/lookup?id=${podcastID}`) .then(response => response.json()) .then(data => this.setState({ podcast: data.results },()=>{ console.log(this.state.podcast) })); 显示为undefined

© www.soinside.com 2019 - 2024. All rights reserved.