【发布时间】:2021-04-11 02:31:38
【问题描述】:
在我的 React 项目中,我将文件 AuthContext.js 中的上下文提取到我的 NavBar 组件中。具体来说,我正在尝试访问状态变量isAuthenticated 和函数toggleAuth。
唯一的问题是,当我尝试加载页面时,出现错误:
TypeError: Cannot destructure property 'isAuthenticated' of 'Object(...)(...)' as it is undefined.
6 | const Navbar = () => {
7 | const { isLightTheme, light, dark } = useContext(ThemeContext);
> 8 | const { isAuthenticated, toggleAuth } = useContext(AuthContext);
9 | const theme = isLightTheme ? light : dark;
10 | return (
11 | <nav style={{ background: theme.ui, color: theme.syntax }}>
我很困惑,因为我以与其他上下文完全相同的方式使用上下文,而且它工作正常(例如,使用我的 ThemeContext.js 文件中的主题)。
关于为什么我的 AuthContext 失败但 ThemeContext 工作的任何建议?
我需要 ThemeContext 和 AuthContext 的 NavBar 组件
NavBar.jsx
import React, { useContext } from 'react';
import { ThemeContext } from '../contexts/ThemeContext';
import { AuthContext } from '../contexts/AuthContext';
const Navbar = () => {
const { isLightTheme, light, dark } = useContext(ThemeContext);
const { isAuthenticated, toggleAuth } = useContext(AuthContext);
const theme = isLightTheme ? light : dark;
return (
<nav style={{ background: theme.ui, color: theme.syntax }}>
<h1>Context App</h1>
<div onClick={() => toggleAuth()}>
{ isAuthenticated ? 'Logged in' : 'Logged out' }
</div>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
);
}
export default Navbar;
我的身份验证上下文文件AuthContext.js:
import React, { Component, createContext } from 'react';
export const AuthContext = createContext();
class AuthContextProvider extends Component {
state = {
isAuthenticated: false
}
toggleAuth = () => {
this.setState({ isAuthenticated: !this.state.isAuthenticated });
}
render() {
return (
<AuthContext.Provider value={{...this.state, toggleAuth: this.toggleAuth}}>
{this.props.children}
</AuthContext.Provider>
);
}
}
export default AuthContextProvider;
主题上下文文件ThemeContext.js
import React, { Component, createContext } from 'react';
export const ThemeContext = createContext();
class ThemeContextProvider extends Component {
state = {
isLightTheme: true,
light: { syntax: '#555', ui: '#ddd', bg: '#eee' },
dark: { syntax: '#ddd', ui: '#333', bg: '#555'}
}
render() {
return (
<ThemeContext.Provider value={{...this.state}}>
{this.props.children}
</ThemeContext.Provider>
);
}
}
export default ThemeContextProvider;
【问题讨论】:
-
你在根组件的AuthContextProvider中包裹了Navbar吗?
标签: reactjs react-context