gpt4 book ai didi

javascript - 无法访问 React 上下文

转载 作者:行者123 更新时间:2023-11-30 13:45:58 24 4
gpt4 key购买 nike

我最近尝试在我的 React 应用程序中实现上下文,但我无法在 chlid 组件上访问我的上下文。

原理如下:index.js 提供了一个上下文,它声明了一个对应于用户登录状态的值(默认为 false)。

如果 App.js 在本地存储中检测到 JWT 存储,则上下文更新为 true 并呈现某个组件。

代码如下:

AppContext.js

import React from 'react'

export const AppContext = React.createContext({
isUserLogged: false
})

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './assets/sakura/app.css'
import App from './components/App'
import * as serviceWorker from './serviceWorker'
import { AppContext } from './context/AppContext'

ReactDOM.render((
<AppContext.Provider>
<App />
</AppContext.Provider>
), document.getElementById('root'));

App.js

import React from 'react'
import Auth from './auth/Auth'
import Main from './main/Main'
import { AppContext } from '../context/AppContext'

class App extends React.Component {
constructor(props) {
super(props)

this.state = {
userToken: localStorage.getItem('spotlight-token'),
isUserLogged: false
}
}

UNSAFE_componentWillMount() {
if (this.state.userToken) this.setState({isUserLogged: true})
}

static contextType = AppContext


render() {
console.log(this.context)

const isUserLogged = this.state.isUserLogged

return isUserLogged ? <Main /> : <Auth />
}
}

export default App

但是问题就在这里,控制台返回undefined,我不明白为什么。

谢谢你的帮助,我知道这听起来有点愚蠢,但我是一个纯粹的宽度上下文初学者,真的很想理解它。

最佳答案

阅读 official docs 中的示例在从嵌套组件更新上下文标题下:

应用程序.js

import {ThemeContext, themes} from './theme-context';
import ThemeTogglerButton from './theme-toggler-button';

class App extends React.Component {
constructor(props) {
super(props);

this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};

// State also contains the updater function so it will
// be passed down into the context provider
this.state = {
theme: themes.light,
toggleTheme: this.toggleTheme,
};
}

render() {
// The entire state is passed to the provider
return (
<ThemeContext.Provider value={this.state}>
<Content />
</ThemeContext.Provider>
);
}
}

function Content() {
return (
<div>
<ThemeTogglerButton />
</div>
);
}

ReactDOM.render(<App />, document.root);

主题切换按钮.js

import {ThemeContext} from './theme-context';

function ThemeTogglerButton() {
// The Theme Toggler Button receives not only the theme
// but also a toggleTheme function from the context
return (
<ThemeContext.Consumer>
{({theme, toggleTheme}) => (
<button
onClick={toggleTheme}
style={{backgroundColor: theme.background}}>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
);
}

export default ThemeTogglerButton;

关于javascript - 无法访问 React 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59327508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com