当我尝试加载页面时出现此错误
错误:(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>
</>
)}
我尝试了一切,但没有任何效果
这可能是因为您将 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>
</>
)}