无法解构 'Object(...)(...)' 的 属性 'currentUser',因为它为 null

Cannot destructure property 'currentUser' of 'Object(...)(...)' as it is null

当我在 Next.js.

中使用 react 的 useContext() 挂钩时,我收到错误 "Cannot destructure property 'currentUser' of 'Object(...)(...)' as it is null"
// Other imports
import CurrentUserContext from "../../contexts/current-user/current-user.context";

class Layout extends React.Component {
  constructor() {
    super();
    this.state = {
      currentUser: null,
    };
  }

  unsubscribeFromAuth = null;

  componentDidMount() {
    // Auth code
  }

  componentWillUnmount() {
    // unsubscribe code
  }

  render() {
    const { children, title } = this.props;
    return (
      <React.Fragment>
        <Head>
          <title>{title}</title>
        </Head>
        <CurrentUserContext.Provider value={this.state.currentUser}>
          <Header />
        </CurrentUserContext.Provider>
        {children}
        <Footer />
      </React.Fragment>
    );
  }
}

export default Layout;

这是错误发生的地方

// Other imports
import CurrentUserContext from "../../contexts/current-user/current-user.context";
import { useContext } from "react";

const Header = () => {
  const { currentUser } = useContext(CurrentUserContext);
  return (
    // Header Jsx
  );
};

export default Header;

这就是我创建上下文文件的方式

import { createContext } from "react";

const CurrentUserContext = createContext(undefined);

export default CurrentUserContext;

错误截图如下

感谢任何帮助。

您的上下文的初始值只是 null,并且您的上下文中没有键 currentUser

this.state = {
  currentUser: null,
};

<CurrentUserContext.Provider value={this.state.currentUser}> // just null

为了能够在您的上下文中解构一个 currentUser,您可以这样做:

<CurrentUserContext.Provider
  value={{
    currentUser: this.state.currentUser
  }}
>

您的上下文值不是要解构的对象,它只是一个值(当前为空),即上下文值只是 this.state.currentUser 的值,而不是 {currentUser: this.state.currentUser }。您可以直接访问它,无需解构。

// Other imports
import CurrentUserContext from "../../contexts/current-user/current-user.context";
import { useContext } from "react";

const Header = () => {
  const currentUser = useContext(CurrentUserContext); // <-- Remove the curly brackets
  return (
    // Header Jsx
  );
};

export default Header;