nextjs中的上下文未定义(0,React__WEBPACK导入模块_0__.useContext)

bxfogqkk  于 2023-01-13  发布在  React
关注(0)|答案(1)|浏览(269)

我为每个路由创建了一个身份验证,我希望在每个路由中都有可用的用户值,这就是我使用上下文的原因。
我做了一个布局组件,我在应用程序中导入后的上下文如下:

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    if (router.pathname == '/' || router.pathname == '/_error') {
      router.push('/login')
    }
  }, [])
  return (
    <AuthProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </AuthProvider>
  )
}

export default MyApp

下面是我的布局组件:

const Layout = ({ children }) => {
  const {loggedInUser} = useContext(AuthContext)
  const router = useRouter()
  useEffect(() => {
    if (router.pathname == '/' || router.pathname == '/_error') {
      ...
    }
  }, [])

  return <div>{children}</div>
}

export default Layout

以下是我的背景:

export const AuthContext = React.createContext()

function AuthProvider(props) {
  const [loggedInUser, setUserLoggedIn] = useState()

  useEffect(() => {
    onAuthStateChanged(auth, (currentUser) => {
      if (!currentUser) {
        setUserLoggedIn(currentUser)
      } else {
      }
    })
  }, [])

  return <AuthContext.Provider value={{
    loggedInUser,
    setUserLoggedIn
  }}>{props.children}</AuthContext.Provider>
}

export default AuthProvider

当我尝试输入一条路径时,我收到此错误TypeError: Cannot destructure property 'loggedInUser' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined.
我希望你能帮我!

euoag5mw

euoag5mw1#

您没有 Package 根组件。

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import AuthContext from "./context/AuthContext";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <AuthContext> // your context <----------------
      <App /> // wrap the root component
    </AuthContext> // your context  <----------------
  </React.StrictMode>
);

相关问题