首页 > 解决方案 > TypeError:无法读取未定义 json react-js 的属性“0”

问题描述

这是我的第一个 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],我会收到错误消息。我究竟做错了什么。

来自 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"
    }
  ]
}

标签: javascriptjsonreactjs

解决方案


将您的状态设置为:

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

推荐阅读