使用console.log时状态未定义

时间:2018-08-30 18:44:35

标签: reactjs

我很困惑。当我尝试 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>
)
  }
}

4 个答案:

答案 0 :(得分:0)

要查看更新的状态,您可以将回调作为第二个参数传递给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)
   }));

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

render() {
const { podcast} = this.state;
return (
  <div>
     {podcast.length &&
      <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>
      </h2> }
   </div>

PS。确保您在API响应中获取数据并且Javascript是异步的。您的render方法将被调用,而无需等待API响应。一旦setState到任何地方,您的组件都将重新呈现。它显示podcast在第一次渲染时未定义

答案 1 :(得分:0)

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

答案 2 :(得分:0)

渲染触发时,您的播客列表为空。当数组为空时,Array.map将有效地运行0个元素,这就是为什么它不会引发错误。 要console.log,您可以首先使用console.log(this.state.podcast[0] && this.state.podcast[0].collectionId)或简单地使用console.log(this.state.podcast[0])检查第一个元素是否存在,如果定义的话,它将呈现整个对象。

答案 3 :(得分:0)

React Lifecycle methods

上图将为您提供一个关于React如何工作的好主意,请检查i = (i + 1) % array.length return array[1] 阶段何时发生。

因此,如果我们将此与您的情况相关,则在调用构造函数调用array[0]后,由于render是一个空数组,在您尝试访问不存在的索引时render()会引发错误值。同样,this.state.podcast函数没有执行,因为console.log是一个空数组。

现在map之后,this.state.podcast获得价值,componentDidMount被再次调用,您将看到集合详细信息。