nextjs 构建的问题。参考错误:窗口未定义

问题描述 投票:0回答:1

我正在尝试构建我的应用程序,但我无法弄清楚为什么会发生这种情况

ReferenceError: window is not defined
,尤其是因为我正在使用“使用客户端”

"use client";
import React, { useEffect, useState } from "react";
import { ref, getDownloadURL } from "firebase/storage";
import { storage } from "./firebase"; // Adjust the import path as needed
import Image from "next/image";

const Hero = () => {
    const [bgImageUrl, setBgImageUrl] = useState("");

    useEffect(() => {
        const fetchImage = async () => {
            const storageRef = ref(storage, "/Hero.jpg"); // Update path accordingly
            try {
                const url = await getDownloadURL(storageRef);
                setBgImageUrl(url);
            } catch (error) {
                console.error("Error fetching image from Firebase:", error);
            }
        };

        fetchImage();
    }, []);

    return (
        <>
            {bgImageUrl && (
                <Image src={bgImageUrl} alt="Hero Image" fill={true} />
            )}
        </>
    );
};

export default Hero;

我已注释掉所有组件,直到只有一个组件出现问题。该组件显示在我的主页上。图像在本地呈现。构建失败。

ReferenceError:窗口未定义 在/home/cjbellmyer/code/green_country/.next/server/app/page.js:512:5749 在4860(/home/cjbellmyer/code/green_country/.next/server/app/page.js:512:16127) 在 t (/home/cjbellmyer/code/green_country/.next/server/webpack-runtime.js:1:127) 在7586(/home/cjbellmyer/code/green_country/.next/server/app/page.js:848:47) 在 t (/home/cjbellmyer/code/green_country/.next/server/webpack-runtime.js:1:127) 在9165(/home/cjbellmyer/code/green_country/.next/server/app/page.js:512:2954) 在 t (/home/cjbellmyer/code/green_country/.next/server/webpack-runtime.js:1:127) 在F(/home/cjbellmyer/code/green_country/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:94693) 在j(/home/cjbellmyer/code/green_country/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:93244) 在 rP (/home/cjbellmyer/code/green_country/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:33905) 生成静态页面(4/4)

导出在以下路径上遇到错误: /页:/

我尝试在我的

useState
中设置默认路径。我尝试使用常规
img
标签而不是图像组件。

typescript firebase next.js build referenceerror
1个回答
0
投票

应该工作但没有。为什么?

首先你需要了解为什么会发生引用错误。

发生这种情况的原因有很多,但最常见的是当您尝试在定义某些内容之前使用它,或者它不存在或在当前范围内不可用时。

现在,虽然“使用客户端”表示特定组件在客户端运行,但它本质上并不能解决与某些客户端代码的兼容性问题。

其中包括浏览器 API,例如 windowdocument

但我并没有这样称呼,事实上这里甚至没有提到 window 。那么为什么会给出参考错误呢?

您没有使用 window,但 firebase 使用。因此,窗口参考错误。

您可以通过确保访问 firebase 的代码仅在客户端上下文中使用来解决此问题。为此,只需检查 window 是否可用。

const fetchImage = async () => {
    // Add this check
    if (typeof window !== 'undefined') {
        const storageRef = ref(storage, "/Hero.jpg"); // Update path accordingly
        try {
            const url = await getDownloadURL(storageRef);
            setBgImageUrl(url);
        } catch (error) {
            console.error("Error fetching image from Firebase:", error);
        }
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.