【问题标题】:How to get an array of all movies from themoviedb?如何从 themoviedb 获取所有电影的数组?
【发布时间】:2022-01-04 17:09:41
【问题描述】:

我不明白如何在一个数组中显示所有电影。在控制台中:

'index.jsx:14 GET https://api.themoviedb.org/3/movie/undefined?api_key=66eb3bde9cca0487f03e78b512b451e4 404
{success: false, status_code: 34, status_message: 'The resource you requested could not be found.'}'

我的代码如下:

import axios from "axios";
import React, { useEffect, useState } from "react";

const Main = () => {

    const [recipes, setRecipes] = useState([]);

    useEffect(() => {
        getRecipes()
    },[])

    const getRecipes = async (id) => {
        const response = await fetch(
          `https://api.themoviedb.org/3/movie/${id}?api_key=66eb3bde9cca0487f03e78b512b451e4`
        );
        const data = await response.json()
        setRecipes(data.id)
        console.log(data)
    }
      
    return(
        <main></main>
    )
}

export default Main;

【问题讨论】:

  • id 没有传递给getRecipes
  • 只需看看 URL:/movie/undefined?!另请注意,您现在需要轮换您的 API 密钥(出于这个原因,您不应将其包含在客户端代码中),因为您已公开共享它。
  • 嘿.. 不要把你的有效 api 密钥放在这里!只需放一个样本或将其替换为API_KEY

标签: reactjs themoviedb-api


【解决方案1】:

您没有向 getRecipes 函数发送 id,所以它会导致错误, 因为 id 在你的函数中是未定义的。

 useEffect(() => {
    getRecipes("2") //Here you should pass the id
},[])

而且,你导入了 axios 却没有使用它。

    const getRecipes = async (id) => {
    const response = await axios.get(`https://api.themoviedb.org/3/movie/${id}?api_key=66eb3bde9cca0487f03e78b512b451e4`);
    const data = response.data;
    console.log(data);
}

【讨论】:

  • 非常感谢!
【解决方案2】:

我假设您正在寻找所有电影列表,而不是电影数据。如果这就是你的意思,那么:-

在 tmdb 文档中,您可以发现电影,docs.

import axios from "axios";
import React, { useEffect, useState } from "react";

const Main = () => {

    const [recipes, setRecipes] = useState([]);

    useEffect(() => {
        getRecipes()
    },[])

    const getRecipes = async () => {
        const response = await fetch(
          `https://api.themoviedb.org/3/discover/movie?api_key=<your_api_key>`
        );
        const data = await response.json()
        setRecipes(data.results) // `results` from the tmdb docs
        console.log(data)
    }
      
    return(
        <main></main>
    )
}

export default Main;

【讨论】:

  • 非常感谢!它帮助了我!
猜你喜欢
  • 2017-08-13
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 2018-06-15
  • 2019-02-18
相关资源
最近更新 更多