简体   繁体   English

当我尝试使用 useEffect 将信息从 firebase 获取到 nextjs 时出现无限循环

[英]Infinity loop when I try to get information from firebase into nextjs using useEffect

I am creating a video section for a project with NextJS .我正在使用NextJS为项目创建视频部分。 I have the videos in firebase storage .我有firebase 存储中的视频。

I created a dynamic route, which launch all videos from an specific reference of the bucket.我创建了一个动态路由,它从存储桶的特定引用启动所有视频。 For example, my bucket is somebucket and has a folder called training with categories (category-1, category-2, category-3).例如,我的存储桶是somebucket并且有一个名为training的文件夹,其中包含类别(category-1、category-2、category-3)。 Each category will be a dynamic route for example localhost:3000/training/category-1 .每个类别都是一个动态路由,例如localhost:3000/training/category-1 Up to here, all good.到这里,一切都很好。

File for dynamic route [id].js动态路由[id].js的文件

// ReactJS
import { useState, useEffect } from "react";

// NextJS
import { useRouter } from "next/router";

// Hooks
import { withProtected } from "../../../hook/route";

// Components
import DashboardLayout from "../../../layouts/Dashboard";

// Firebase
import { getMetadata, listAll, ref } from "firebase/storage";
import { storage } from "../../../config/firebase";

// Utils
import capitalize from "../../../utils/capitalize";
import { PlayIcon } from "@heroicons/react/outline";

function Video() {
  // States
  const [videos, setVideos] = useState([]);

  // Routing
  const router = useRouter();
  const { id } = router.query;

  // Reference
  const reference = ref(storage, `training/${id}`);

  useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos);
      });
    }

    exec();
  }, [reference, videos]);

  return (
    <DashboardLayout>
      <h2>{capitalize(reference.name)}</h2>
      <section>
        <video controls controlsList="nodownload">
          <source
            src="https://example.com"
            type="video/mp4"
          />
        </video>
        <ul role="list" className="divide-y divide-gray-200 my-4">
          {videos.map((video) => (
            <li key={video.name} className="py-4 flex">
              <div className="ml-3 flex flex-row justify-start items-center space-x-3">
                <PlayIcon className="w-6 h-6 text-gray-600" />
                <p className="text-sm font-medium text-gray-900">
                  {video.name}
                </p>
              </div>
            </li>
          ))}
        </ul>
      </section>
    </DashboardLayout>
  );
}

export default withProtected(Video);

I make a dynamic reference based on route with:我根据路线进行动态参考:

// Reference
const reference = ref(storage, `training/${id}`);

This reference will be listed with listAll method as mentioned before:如前所述,此引用将使用 listAll 方法列出:

useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos);
      });
    }

exec();
}, [reference]);

I push the elements to an state as an array, then the state will be iterated by a component.我将元素作为数组推送到 state,然后 state 将由组件迭代。 Apparently work fines, but I got an infinity loop:显然工作罚款,但我有一个无限循环:

在此处输入图像描述

Anyone has an idea why this happen?任何人都知道为什么会这样?

Im not sure what the issue is but isn't it better to have only the id param in the useEffects array dependency list.我不确定问题出在哪里,但在 useEffects 数组依赖项列表中只包含 id 参数不是更好吗?

I think this would be better as you only have different videos depending on the route so only when the route changes does the useEffect have to rerun.我认为这会更好,因为您只有不同的视频,具体取决于路线,因此只有当路线发生变化时,useEffect 才必须重新运行。

Your problem is possibly from this你的问题可能来自于此

useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos); //update `videos` again --> call `useEffect` again due to `videos` update
      });
    }

    exec();
  }, [reference, videos]); //`videos` dependency 

You should remove videos in your useEffect dependency list您应该删除useEffect依赖列表中的videos

useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos);
      });
    }

    exec();
  }, [reference]);

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

相关问题 如何使用 NextJs API、Firebase Firestore、axios 和 TypeScript 从 Firebase 集合中获取数据? - How do I get data from Firebase collection using NextJs API, Firebase Firestore, axios and TypeScript? 首次加载页面时未定义 firebase 和 nextjs 的 useEffect - useEffect with firebase and nextjs undefined when page first loads 当我尝试从 firebase 获取数据时,控制台出现错误 - when I try to get a data from the firebase I get error in the console UseEffect 无限循环与 Firebase - UseEffect infinite loop with Firebase 我无法从 expo 中的数据库 (firebase) 获取信息 - I can't get information from the database (firebase) in expo 从 Firebase Firestore 提取信息时出现错误 - I'm getting an error when pulling information from Firebase Firestore 当我尝试使用 termux 在 Android 上安装 firebase 时,我该如何解决这个问题? - How can I fix this problem I'm getting when I try to install firebase on Android using termux? 当我使用 import * as firebase from 'firebase' 导入 firebase 时;? - when I import firebase using import * as firebase from 'firebase';? 当我尝试部署 firebase function (基本你好世界)时,我收到此错误:FetchError:无法获取本地颁发者证书 - When I try to deploy firebase function (basic hello world), i get this error :FetchError: unable to get local issuer certificate 使用 useEffect 无限循环 - infinite loop using useEffect
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM