簡體   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