当我在 Next.js 中使用 react 中的 useContext() 挂钩时,我收到错误“无法解构 'Object(...)(...)' 的属性 'currentUser',因为它为空”。
// 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;
任何帮助表示赞赏。