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

时间:2020-05-22 06:08:55

标签: reactjs next.js react-context context-api use-context

当我在Next.js中使用useContext()挂钩时,收到错误消息“无法解构Object(...)(...)'的属性'currentUser',因为它为null”。 / p>

// 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;

下面的错误屏幕截图 Cannot destructure property 'currentUser' of 'Object(...)(...)' as it is null

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

上下文的初始值仅为null,上下文中没有键currentUser

this.state = {
  currentUser: null,
};

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

要能够在您的上下文中破坏currentUser,可以执行以下操作:

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

答案 1 :(得分:1)

您的上下文值不是要解构的对象,它只是一个值(当前为null),即上下文值只是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;