【问题标题】:React Project. Having an issue fetching data using parameter and getting infinite loops反应项目。使用参数获取数据并获取无限循环时出现问题
【发布时间】:2021-04-04 00:23:08
【问题描述】:

这个项目有多个问题,确实给我带来了问题。我现在要发布 API 密钥,以防任何人也需要尝试完成此操作,然后我会从 API 主机请求新的 API 密钥。

所以我的问题是,我调用了一个电影数据库 API,它为我提供了本周 20 部热门电影。我将该数据设置为我称为“趋势”的状态。没问题。然后我绘制了趋势图并列出了电影 ID# 的列表。我将这些保存到一个名为“movieId”的状态。这些 id 很重要,因为我需要它们来最终调用不同的端点。它需要moviesID 来返回数据,该数据为我提供了指向某人可以购买或观看电影的链接。每个电影 ID 提供者的链接列表是我的主要目标。我需要这些链接,这样我就可以为每部电影分配它的提供者链接,这样用户就可以点击电影图片并被引导到他们可以观看电影的地方。不过,我还不需要做到这一点。现在,我只需要链接。我用下面的代码尝试这个,但我得到的只是无限循环,输入错误说我 US.link 无效等。我做错了,但我不知道它是什么,请帮忙!

这里是沙盒的链接---->React Sandbox Project

import "./styles.css";
import React, { useEffect, useState } from "react";

export default function App() {
  const [trending, setTrending] = useState([]);
  const [movieId, setMovieId] = useState("");
  const [link, setLink] = useState("");
  // set trending to get the movies data.

  //set movieID to get the movie ID's

  //set link to get the providerlink that belongs to each movieID.

  useEffect(() => {
    const trendUrl =
      "https://api.themoviedb.org/3/trending/movie/week?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
    fetch(trendUrl)
      .then((response) => response.json())
      .then((data) => {
        setTrending(data.results);
      })
      .catch((error) => {
        console.log("Error!! Data interupted!:", error);
      });
  }, []);

  const Collection = () => {
    trending.map((item) => setMovieId(item.id));
  };
  Collection();

  function Linked() {
    const url = `https://api.themoviedb.org/3/movie/${movieId}/watch/providers?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95`;
    fetch(url)
      .then((res) => res.json())
      .then((res) => console.log(res.results.US.link));

    //Gives movie ID and adds it to properlink
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
```

【问题讨论】:

    标签: javascript reactjs api jsx


    【解决方案1】:

    你有一些关于如何在 react 中使用这种方法的问题,我将在下面详细介绍:

    破坏您的应用程序的第一个问题是您在渲染生命周期中的 .map 方法中设置状态,因此您每次都调用以重新渲染您的组件,因此它永远不会停止。如果您需要存储 id 列表,您应该执行以下操作:

    首先将movieId状态删除为一个你不需要再使用它的数组。

     const [movieId, setMovieId] = useState("");
    

    然后,您应该修改您的Collection 函数,并通过以下方式使用 map 创建一个变量来存储 id 列表:

    const moviesIdCollections =  trending.map((item) => (item.id));
    

    现在,您的应用程序将再次运行,并且您的 ids 集合已准备好在您要在组件中使用它的任何地方使用。

    现在,如果您想列出每部电影的详细信息,我建议您使用接收电影 id 的 prop 构建另一个组件,然后在 useEffect 挂钩中调用它,如下例所示:

        function MovieDetail(props) {
      const [movie, setMovie] = useState(null);
      const {id} = props;
    
      useEffect(()=>{
        getMovieDetail(id)
        .then((res) => res.json())
        .then((res) => setMovie(res));
      }, [id])
      
      return movie ? <code>{JSON.stringify(movie)}</code> : <p>Probably fetching data</p>;
      
    }
    

    我看到您刚刚开始使用 react,因此我建议您阅读 the react lifecycle in docs.the react way 以了解如何在 react 中正确构建组件。

    https://codesandbox.io/s/blazing-dawn-4w8b2?file=/src/App.js

    您好,希望您一切顺利。

    【讨论】:

    • 很多人在这篇文章之后点击并阅读了更多正确构建的组件。感谢您的回复,这对我帮助很大!
    【解决方案2】:

    问题是您在 useEffect() 之外调用 Collection() 并且不断被调用。您应该在 useEffect(); 中进行调用

    看看这个:

        import "./styles.css";
    import React, { useEffect, useState } from "react";
    
    export default function App() {
      const [trending, setTrending] = useState([]);
      const [movieId, setMovieId] = useState("");
      const [link, setLink] = useState("");
      // set trending to get the movies data.
    
      //set movieID to get the movie ID's
    
      //set link to get the providerlink that belongs to each movieID.
    
      useEffect(() => {
        const trendUrl =
          "https://api.themoviedb.org/3/trending/movie/week?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
        fetch(trendUrl)
          .then((response) => response.json())
          .then((data) => {
            setTrending(data.results);
            Collection();
          })
          .catch((error) => {
            console.log("Error!! Data interupted!:", error);
          });
      }, []);
    
      const Collection = () => {
        trending.map((item) => setMovieId(item.id));
      };
    
      function Linked() {
        const url = `https://api.themoviedb.org/3/movie/${movieId}/watch/providers?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95`;
        fetch(url)
          .then((res) => res.json())
          .then((res) => console.log(res.results));
    
        //Gives movie ID and adds it to properlink
      }
    
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
          <button onClick={Linked}>SEE RESULTS</button>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2022-01-12
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2021-11-22
      • 2020-04-21
      相关资源
      最近更新 更多