简体   繁体   English

类型错误:当我尝试访问 API 调用数据时,无法读取未定义的属性“映射”

[英]TypeError: Cannot read property 'map' of undefined when I am trying to access API call data

I am trying to make a movie search app with React and have made an API call to The Movie Database API.我正在尝试使用 React 制作电影搜索应用程序,并已对电影数据库 API 进行了 API 调用。 I have this form and what I am trying to do is get the data of the movie that I am searching for.我有这个表格,我想要做的是获取我正在搜索的电影的数据。

I am not able to access the data from the API call, and I get this error of "Uncaught TypeError: Cannot read property 'map' of undefined"我无法从 API 调用访问数据,并且收到“未捕获的类型错误:无法读取未定义的属性‘地图’”的错误消息

I have two js files: 1 index.js我有两个 js 文件:1 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import SearchMovies from "./searchMovies";
import './style.css';

class Main extends React.Component {
  render() {
    return (
      <div className="container">
        <h1 className="title">React Movie Search</h1>
        <SearchMovies/>
      </div>
  
    );
  }
}

ReactDOM.render(<Main />, document.getElementById('root'));

The second file is searchMovies.js第二个文件是 searchMovies.js

import React, {useState} from "react";

export default function SearchMovies(){

//states- input query, movies
const [query, setQuery] = useState('');
const [movies, setMovies] = useState([]);

const searchMovies = async (e) => {
    e.preventDefault();
    
    const url = `https://api.themoviedb.org/3/movie/550? 
    api_key=api_key&language=en-US&query=${query}&page=1&
        include_adult=false`;

        try {
            const res = await fetch(url);
            const data  = await res.json();
            setMovies(data.results);
        }catch(err){
            console.error(err);
        }
}


return(
    <div>
        <form className="form" onSubmit={searchMovies}>
            <label htmlFor="query" className="Label">Movie Name</label>

            <input className="input" type="text" name="query" placeholder="i.e. Jurassic 
                Park"
                value={query} onChange={(e) => setQuery(e.target.value)}
            />

            <button className="button" type="submit">Search</button>
        </form>
        <div className="card-list">
            {movies.map(movie => (
                <div className="card">
                    <img className="card--image"
                        src={`https://image.tmdb.org/t/p/w185_and_h278_bestv2/
                        ${movie.poster_path}`}
                        alt={movie.title + ' poster'}
                        />

                </div>
            ))}
        </div>
      </div>
    )
}

Can somebody tell me what I am doing wrong here?有人可以告诉我我在这里做错了什么吗? I am new to React.我是 React 的新手。 Many thanks!非常感谢!

Your API response an object, not an array that's why the map function not working.您的 API 响应一个对象,而不是一个数组,这就是 map 函数不起作用的原因。

See Your API response:查看您的 API 响应:

{"adult":false,"backdrop_path":"/rr7E0NoGKxvbkb89eR1GwfoYjpA.jpg","belongs_to_collection":null,"budget":63000000,"genres":[{"id":18,"name":"Drama"}],"homepage":"http://www.foxmovies.com/movies/fight-club","id":550,"imdb_id":"tt0137523","original_language":"en","original_title":"Fight Club","overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground "fight clubs" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.","popularity":46.801,"poster_path":"/pB8BM7pdSp6B6Ih7QZ4DrQ3PmJK.jpg","production_companies":[{"id":508,"logo_path":"/7PzJdsLGlR7oW4J0J5Xcd0pHGRg.png","name":"Regency Enterprises","origin_country":"US"},{"id":711,"logo_path":"/tEiIH5QesdheJmDAqQwvtN60727.png","name":"Fox 2000 Pictures","origin_country":"US"},{"id":20555,"logo_path":"/hD8yEGUBlHOcfHYbujp71vD8gZp.png","name":"Taurus Film","origin_cou {"成人":false,"backdrop_path":"/rr7E0NoGKxvbkb89eR1GwfoYjpA.jpg","belongs_to_collection":null,"budget":63000000,"genres":[{"id":18,"name":"Drama"} ],"主页":"http://www.foxmovies.com/movies/fight-club","id":550,"imdb_id":"tt0137523","original_language":"en","original_title": “搏击俱乐部”,“概述”:“一个定时炸弹失眠症和一个狡猾的肥皂推销员将原始男性侵略转化为一种令人震惊的新疗法。他们的概念流行起来,每个城镇都形成了地下“搏击俱乐部”,直到一个古怪的人挡道并点燃了一个失控的螺旋走向遗忘。","popularity":46.801,"poster_path":"/pB8BM7pdSp6B6Ih7QZ4DrQ3PmJK.jpg","production_companies":[{"id":508, "logo_path":"/7PzJdsLGlR7oW4J0J5Xcd0pHGRg.png","name":"Regency Enterprises","origin_country":"US"},{"id":711,"logo_path":"/tEiH5QesdheJmDAq7wv7"png"png"png" :"Fox 2000 Pictures","origin_country":"US"},{"id":20555,"logo_path":"/hD8yEGUBlHOcfHYbujp71vD8gZp.png","name":"Taurus Film","origin_cou ntry":"DE"},{"id":54051,"logo_path":null,"name":"Atman Entertainment","origin_country":""},{"id":54052,"logo_path":null,"name":"Knickerbocker Films","origin_country":"US"},{"id":25,"logo_path":"/qZCc1lty5FzX30aOCVRBLzaVmcp.png","name":"20th Century Fox","origin_country":"US"},{"id":4700,"logo_path":"/A32wmjrs9Psf4zw0uaixF0GXfxq.png","name":"The Linson Company","origin_country":""}],"production_countries":[{"iso_3166_1":"DE","name":"Germany"},{"iso_3166_1":"US","name":"United States of America"}],"release_date":"1999-10-15","revenue":100853753,"runtime":139,"spoken_languages":[{"iso_639_1":"en","name":"English"}],"status":"Released","tagline":"Mischief. ntry":"DE"},{"id":54051,"logo_path":null,"name":"Atman Entertainment","origin_country":""},{"id":54052,"logo_path":null ,"name":"Knickerbocker Films","origin_country":"US"},{"id":25,"logo_path":"/qZCc1lty5FzX30aOCVRBLzaVmcp.png","name":"20th Century Fox","origin_country" :"US"},{"id":4700,"logo_path":"/A32wmjrs9Psf4zw0uaixF0GXfxq.png","name":"The Linson Company","origin_country":""}],"production_countries":[{" iso_3166_1":"DE","name":"Germany"},{"iso_3166_1":"US","name":"United States of America"}],"release_date":"1999-10-15", "revenue":100853753,"runtime":139,"spoken_languages":[{"iso_639_1":"en","name":"English"}],"status":"Released","tagline":"Mischief . Mayhem.混乱。 Soap.","title":"Fight Club","video":false,"vote_average":8.4,"vote_count":20153} Soap.","title":"Fight Club","video":false,"vote_average":8.4,"vote_count":20153}

I made a jsfiddle with your code for testing: https://jsfiddle.net/hqm6rcpf/我用你的测试代码做了一个 jsfiddle: https ://jsfiddle.net/hqm6rcpf/

const url = `https://api.themoviedb.org/3/movie/550? 
    api_key=api_key&language=en-US&query=${query}&page=1&
        include_adult=false`;

This code is invalid.此代码无效。 You cannot add line breaks in a URL.您不能在 URL 中添加换行符。

By changing to this, I was able to make it work:通过改变这个,我能够使它工作:

const url = `https://api.themoviedb.org/3/search/movie?api_key=api_key&language=en-US&query=${query}&page=1&include_adult=false`;

first of all, never share your personal api key on the internet!!首先,永远不要在互联网上分享您的个人 api 密钥!!

 const data  = await res.json();

Why use await again when you have already fetched the data?既然已经获取了数据,为什么还要再次使用 await? also, if the response is json, it's JSON.parse(res).此外,如果响应是 json,则是 JSON.parse(res)。

Next, have you actually looked at the data you are getting?接下来,你是否真的看过你得到的数据? Try console logging it.尝试控制台记录它。 From what I can tell, it's an object, not an array, so you can't use map.据我所知,它是一个对象,而不是一个数组,所以你不能使用 map。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试访问嵌入的Google地图时,为什么会出现无法读取未定义的属性“ getCenter”的问题? - Why am I getting Cannot read property 'getCenter' of undefined when trying to access my embed google map? 当尝试访问 hypixel api 中的“pricePerUnit”时,出现错误:TypeError: Cannot read property 'pricePerUnit' of undefined - When trying to access the "pricePerUnit" in the hypixel api, i get the error: TypeError: Cannot read property 'pricePerUnit' of undefined 我正在尝试从数据库中获取 map mydata 但我收到此错误。 TypeError:无法读取未定义的属性“地图” - I am trying to map mydata from the database but i am getting this error. TypeError: Cannot read property 'map' of undefined 我试图 map 数据库中的数据并收到此错误。 TypeError:无法读取未定义的属性“地图” - I trying to map the data from the database and getting this error. TypeError: Cannot read property 'map' of undefined 使用 useEffect 调用 API。 当尝试映射用户时,它说 TypeError: Cannot read property 'map' of undefined - Calling an API With useEffect . when Trying to mapping user it is saying TypeError: Cannot read property 'map' of undefined 类型错误:无法读取未定义的属性“then”。 当我尝试运行 updatefirst 函数时出现此错误 - TypeError: Cannot read property 'then' of undefined. Getting this error when I am trying to run updatefirst function 未捕获的类型错误:尝试显示数据时无法读取未定义的属性“0” - Uncaught TypeError: Cannot read property '0' of undefined when trying to display data TypeError 从 Api 获取数据时无法读取未定义的属性“映射” - TypeError Cannot read property 'map' of undefined when getting data from Api TypeError:检索API数据时无法读取未定义的属性“ temp” - TypeError: cannot read property “temp” of undefined when retreiving API data 类型错误:无法读取未定义的属性(读取“地图”)。 当我尝试通过一系列加密货币 map 时抛出错误 - TypeError: Cannot read properties of undefined (reading 'map'). Error being thrown when I am trying to map over an array of cryptocurrencies
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM