TypeError:无法读取未定义的json react-js的属性“0”

时间:2018-06-11 15:45:11

标签: javascript json reactjs

这是我的第一个React应用程序,我之前也使用过api也是出于同样的目的而且它工作但没有使用React。我做错了什么。

import React, { Component } from 'react'
import CardArray from './CardArray'
class Popular extends Component {

   constructor() {
        super()

        this.state = {
            movies : {}
        }
    }

    componentDidMount() {

        fetch('https://api.themoviedb.org/3/movie/popular?api_key=key&language=en-US&page=1')
      .then(response=> response.json())
      .then(response => {this.setState({ movies : response})});

    }

    render() {

        var popularMovies = this.state.movies.results[0]; //this line has error

        console.log(popularMovies)

        return(
            <div>
                <h1 className="popular-heading">POPULAR MOVIES</h1>
                <CardArray popularMovies={popularMovies}/>
            </div>
        );

    };

}
export default Popular;

我正在尝试从JSON格式的API获取数据。我获取代码并将其记录在控制台中,整个JSON文件就在那里,但如果尝试从JSON文件中获取结果[0],我会得到错误。我做错了什么。

Error from Chrome

我得到的json是(从结果数组中删除了一些对象)

    {
  "page": 1,
  "total_results": 19865,
  "total_pages": 994,
  "results": [
    {
      "vote_count": 397,
      "id": 351286,
      "video": false,
      "vote_average": 6.7,
      "title": "Jurassic World: Fallen Kingdom",
      "popularity": 395.188765,
      "poster_path": "/c9XxwwhPHdaImA2f1WEfEsbhaFB.jpg",
      "original_language": "en",
      "original_title": "Jurassic World: Fallen Kingdom",
      "genre_ids": [
        28,
        12,
        878
      ],
      "backdrop_path": "/t0Kn7twXduHeFhOpTW2Gncu9l5F.jpg",
      "adult": false,
      "overview": "A volcanic eruption threatens the remaining dinosaurs on the island of Isla Nublar, where the creatures have freely roamed for several years after the demise of an animal theme park known as Jurassic World. Claire Dearing, the former park manager, has now founded the Dinosaur Protection Group, an organization dedicated to protecting the dinosaurs. To help with her cause, Claire has recruited Owen Grady, a former dinosaur trainer who worked at the park, to prevent the extinction of the dinosaurs once again.",
      "release_date": "2018-06-06"
    },
    {
      "vote_count": 2107,
      "id": 383498,
      "video": false,
      "vote_average": 7.8,
      "title": "Deadpool 2",
      "popularity": 218.858604,
      "poster_path": "/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg",
      "original_language": "en",
      "original_title": "Deadpool 2",
      "genre_ids": [
        28,
        35,
        878
      ],
      "backdrop_path": "/3P52oz9HPQWxcwHOwxtyrVV1LKi.jpg",
      "adult": false,
      "overview": "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.",
      "release_date": "2018-05-15"
    },
    {
      "vote_count": 6657,
      "id": 284053,
      "video": false,
      "vote_average": 7.4,
      "title": "Thor: Ragnarok",
      "popularity": 190.16373,
      "poster_path": "/rzRwTcFvttcN1ZpX2xv4j3tSdJu.jpg",
      "original_language": "en",
      "original_title": "Thor: Ragnarok",
      "genre_ids": [
        28,
        12,
        14,
        878,
        35
      ],
      "backdrop_path": "/kaIfm5ryEOwYg8mLbq8HkPuM1Fo.jpg",
      "adult": false,
      "overview": "Thor is on the other side of the universe and finds himself in a race against time to get back to Asgard to stop Ragnarok, the prophecy of destruction to his homeworld and the end of Asgardian civilization, at the hands of an all-powerful new threat, the ruthless Hela.",
      "release_date": "2017-10-25"
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

将状态设置为:

this.state = {
    movies : {
        results: []
    }
}

所以,this.state.movie.results[]现在存在。没有错误。而不是

<CardArray popularMovies={popularMovies}/>

你应该做

<CardArray popularMovies={this.state.movies.results[0]}/>

在您的方式上,您在请求完成之前尝试获取结果。因此,这就是您收到错误的原因,因为请求尚未完成。

删除下面的一行

var popularMovies = this.state.movies.results[0]; //this line has error