我创建了一个上下文来在登录后显示电子邮件(下一个js和firebase),但是当我尝试在导航栏中显示电子邮件时出现错误

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

当我尝试加载页面时出现此错误

错误:(0,lib_AuthContext__WEBPACK_IMPORTED_MODULE_1_.useAuth)不是一个函数

顺便说一句,登录和注册有效

AuthContext.js

"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { onAuthStateChanged, getAuth } from "firebase/auth";
import { auth } from "./firebase";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      setUser(user);
    });

    return () => unsubscribe();
  }, []);

  return (
    <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);

导航栏.jsx

const { user } = useAuth();
{user ? (
          <span className="navbar-user-email">{user.email}</span>
        ) : (
          <>
            <Link href="/auth/login" className="navbar-link">
              Login
            </Link>
            <Link href="/auth/signup" className="navbar-link">
              Sign Up
            </Link>
          </>
        )}

我尝试了一切,但没有任何效果

javascript firebase next.js
1个回答
0
投票

这可能是因为您将 useContext 嵌套在不必要的函数调用中

而不是这样做:

export const useAuth = () => useContext(AuthContext);

在 AuthContext.js 中

你应该在 Navbar.jsx 中执行此操作

import {AuthContext} from "./AuthContext"


const { user } = useContext(AuthContext);
{user ? (
          <span className="navbar-user-email">{user.email}</span>
        ) : (
          <>
            <Link href="/auth/login" className="navbar-link">
              Login
            </Link>
            <Link href="/auth/signup" className="navbar-link">
              Sign Up
            </Link>
          </>
        )}
© www.soinside.com 2019 - 2024. All rights reserved.