当我在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;
感谢您的帮助。
答案 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;