Uncaught TypeError: Cannot destructure property 'xxx' of 'useAuth(...)' as it is undefined

Uncaught TypeError: Cannot destructure property 'xxx' of 'useAuth(...)' as it is undefined

使用 React Context 和 Hooks 我正在创建一个名为 AuthProvider 的提供程序,我从 useAuth Hook 调用该上下文来使用它。我有一个名为 Login 的组件,我在其中调用 Hook 来访问 AuthProvider,如下所示:

import useAuth from '../hooks/useAuth'

const Login = () => {

  const { hello } = useAuth() 

  console.log(hello);

...

在 AuthContext 中,我将变量“hello”传递给上下文的子项。

授权提供者:

const AuthContext = createContext()

const AuthProvider = ({children}) => {

    const hello= 'hello'

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

export {
     AuthProvider
}

export default AuthContext

UseAuth 挂钩:

import { useContext } from "react";
import AuthContext from "../context/AuthProvider";

const useAuth  = () => {

     return useContext(AuthContext)

}

export default useAuth

这是错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'hello')

问题是您使用上下文但未包装在上下文提供程序下的组件

要修复,请将组件或将组件作为子组件的根组件包装在上下文提供程序下

<AuthProvider>
  <Login />
</AuthProvider>

演示

参考资料

https://reactjs.org/docs/context.html

https://reactjs.org/docs/hooks-reference.html#usecontext