为什么我的 nextjs 组件渲染两次?

这是一个从 firebase 存储中渲染数据并将其列出的组件。该函数要做的就是将从 firebase 存储中提取的视频设置为 useState。这样我就可以调用视频并将其映射到一个新组件中,该组件恰好是一个按钮列表。它工作得比较好,问题是组件渲染了两次,第一次它没有保存状态中的视频,第二次它做了。换句话说,组件不会等待视频保存在状态,而是简单地渲染自己,导致带有视频标题的按钮列表没有显示。

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

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

// Seo
import Seo from "../../../components/Seo";

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

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

// Firebase
import { getDownloadURL, 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([]);
  const [videoActive, setVideoActive] = useState(null);

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

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

  // Check if path is empty

  function getVideos() {
    let items = [];
    listAll(reference).then((res) => {
      res.items.forEach(async (item) => {
        getDownloadURL(ref(storage, `training/${id}/${item.name}`)).then(
          (url) => {
            items.push({
              name: item.name.replace("-", " "),
              href: item.name,
              url,
            });
          }
        );
      });
    });
    setVideos(items);
  }

  useEffect(() => {
    getVideos();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  console.log(videos);

  return (
    <>
      <Seo
        title={`${capitalize(id)} Training - Dashboard`}
        description={`${capitalize(
          id
        )} training for all Every Benefits Agents.`}
      />
      <DashboardLayout>
        <h2>{capitalize(reference.name)}</h2>
        <section>
          <video controls controlsList="nodownload">
            {videoActive && <source src={videoActive} type="video/mp4" />}
          </video>
          <ul role="list" className="divide-y divide-gray-200 my-4">
            {videos.map((video, index) => (
              <button key={index} className="py-4 flex">
                <div className="w-full 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>
              </button>
            ))}

            {console.log("Component rendered")}
          </ul>
        </section>
      </DashboardLayout>
    </>
  );
}

export default withProtected(Video);

这是组件如何开始渲染的示例:

enter image description here

任何人都知道为什么会这样?

stack overflow Why my nextjs component is rendering twice?
原文答案

答案:

作者头像

我在这个线程中找到了答案。 https://github.com/vercel/next.js/issues/35822

简而言之,这个问题是关于 React 18 严格模式的。您可以阅读 React 18 Strict Mode 中的新内容。

如果您不使用严格模式,则不应发生。如果不是很重要,可以在 next.config.js 中关闭 React Strict Mode。文件如下图。

const nextConfig = {
  reactStrictMode: false
}

module.exports = nextConfig