繁体   English   中英

无法访问 React 上下文

[英]Can't access to React Context

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

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

如果App.js在本地存储中检测到 JWT 存储,那么上下文将更新为true并渲染某个组件。

这是代码:

AppContext.js

import React from 'react'

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

索引.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'));

应用程序.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 ,我不明白为什么。

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

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

应用程序.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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM