繁体   English   中英

当我尝试添加 API 密钥时,出现错误:TypeError: items.map is not a function

[英]I get the error: TypeError: items.map is not a function, when I try to add my API key

当我使用此组件时,出现以下错误。 当我仅将完全相同的函数与另一个 API 一起使用时,它就起作用了,并且我从 API 获得了输出。

类型错误:items.map 不是函数 ApiInfo.render C:/Users/32479/mikiesoftMovies2/cinemaReact-master/src/components/ApiInfo.js:35

 32 | 33 | return ( 34 | <div className = "App"> 35 | <h1> Fetch data from an api in react </h1> { | ^ 36 | items.map((item) => ( 37 | <ol key = { item.id } > 38 | Title: { item.original_title }

当我用另一个 API 尝试它时,它起作用了,我根本没有错误。 我是 React 的新手,所以我不知道出了什么问题。

这是我的代码(带有给我错误的 API)它只是一个从 API 请求信息并将其放入ol

import React from "react";

export class ApiInfo extends React.Component {
    
    // Constructor 
    constructor(props) {
        super(props);
   
        this.state = {
            items: [],
            DataisLoaded: false
        };
    }
   
    // ComponentDidMount is used to
    // execute the code 
    componentDidMount() {
        fetch(
"https://api.themoviedb.org/3/movie/top_rated?api_key=55957fcf3ba81b137f8fc01ac5a31fb5&language=en-US&page=1")
            .then((res) => res.json())
            .then((res) => {
                this.setState({
                    items: res,
                    DataisLoaded: true
                });
            })
    }
    render() {
        const { DataisLoaded, items } = this.state;
        if (!DataisLoaded) return <div>
            <h1> Please wait some time.... </h1> </div> ;
   
        return (
        <div className = "App">
            <h1> Fetch data from an api in react </h1>  {
                items.map((item) => ( 
                <ol key = { item.id } >
                    Title: { item.original_title }
                    </ol>
                ))
            }
        </div>
    );
}
}
   
   
export default ApiInfo;

我将添加一个来自我正在使用的 API 的 json 示例:来自 API unminified 的 json

您正在寻找的电影项目由电影数据库 API 在res.results中返回,而不是在res

this.setState({
    items: res.results,
    DataisLoaded: true
});

请参阅API 参考以了解评分最高的电影

附带说明一下,处理 HTTP 错误情况是一种很好的做法,因此请考虑向 fetch 调用添加一个 catch 块。

变量items不是数组。 因此map不是函数。 打印出变量res ,您将看到隐藏在后面的内容以及您必须分配给items

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM