当我尝试访问 API 调用数据时,TypeError:无法读取未定义的属性“map”
我正在尝试使用 React 制作电影搜索应用,并对电影数据库 API 进行了 API 调用。我有此表单,我想做的是获取我正在搜索的电影的数据。
我无法从 API 调用访问数据,并且收到此错误“Uncaught TypeError:无法读取未定义的属性‘map’”
我有两个 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'));
第二个文件是 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>
)
}
有人能告诉我我在这里做错了什么吗?我是 React 新手。 非常感谢!
您的 API 响应是一个对象,而不是数组,这就是 map 函数不起作用的原因。
查看您的 API 响应:
{"adult":false,"backdrop_path":"/rr7E0NoGKxvbkb89eR1GwfoYjpA.jpg","belongs_to_collection":null,"budget":63000000,"genres":[{"id":18,"name":"戏剧"}],"homepage":"http://www.foxmovies.com/movies/fight-club","id":550,"imdb_id":"tt0137523","original_language":"en","original_title":"搏击俱乐部","overview":"一个定时炸弹般的失眠症患者和一个狡猾的肥皂推销员将原始的男性攻击性转化为一种令人震惊的新疗法。他们的概念流行起来,地下每个城镇都成立了“搏击俱乐部”,直到一个怪人的出现,引发了一场失控的毁灭性漩涡。","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":"美国"},{"id":20555,"logo_path":"/hD8yEGUBlHOcfHYbujp71vD8gZp.png","name":"Taurus Film","origin_country":"德国"},{"id":54051,"logo_path":null,"name":"Atman Entertainment","origin_country":""},{"id":54052,"logo_path":null,"name":"Knickerbocker Films","origin_country":"美国"},{"id":25,"logo_path":"/qZCc1lty5FzX30aOCVRBLzaVmcp.png","name":"20 世纪Fox","origin_country":"美国"},{"id":4700,"logo_path":"/A32wmjrs9Psf4zw0uaixF0GXfxq.png","name":"林森公司","origin_country":""}],"production_countries":[{"iso_3166_1":"DE","name":"德国"},{"iso_3166_1":"US","name":"美利坚合众国"}],"release_date":"1999-10-15","revenue":100853753,"runtime":139,"spoken_languages":[{"iso_639_1":"en","name":"英语"}],"status":"已发布","tagline":"恶作剧。混乱。肥皂剧。","title":"搏击俱乐部","video":false,"vote_average":8.4,"vote_count":20153>
我使用您的代码制作了一个 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`;
此代码无效。您无法在 URL 中添加换行符。
通过更改为此,我能够使其正常工作:
const url = `https://api.themoviedb.org/3/search/movie?api_key=api_key&language=en-US&query=${query}&page=1&include_adult=false`;
首先, 切勿在互联网上分享您的个人 API 密钥!!
const data = await res.json();
既然已经获取了数据,为什么还要再次使用 await? 此外,如果响应是 json,则为 JSON.parse(res)。
接下来,您是否真的查看过所获取的数据? 尝试控制台记录它。 据我所知,它是一个对象,而不是数组,因此您不能使用 map。