上下文的值未定义

Value of context is undefiend

我是 React 的新手,我正在为一些应该很容易的事情而苦苦挣扎。 当用户登录时,我想在导航栏上保存他们的上下文和 display/hide 东西。 但是,当我将它传递给 children.

时,上下文的值是未定义的

可以找到上下文指南here

这是我的代码src/App.js:

export default class App extends Component {
    static displayName = App.name;
    render() {
        return (
            <Layout>
                <Route exact path='/' component={Login} />
                <Route path='/fetch-data' component={FetchData} />
            </Layout>
        );
    }
}

src/userContext:

import React from 'react';
const userContext = React.createContext({ user: {} });
export { userContext };

src/components/Layout.js:

import { userContext } from '../userContext';
export class Layout extends Component {
    static displayName = Layout.name;

    constructor(props) {
        super(props);
        this.state = {
            user: { 'test123': 'test456' }
        };
        this.logout = this.logout.bind(this);
    }
    componentDidMount() {
        // get and set currently logged in user to state
    }
    logout() {
        this.setState({ user: {} });
    }
    render() {
        const value = {
            user: this.state.user,
            logoutUser: this.logout
        }
        return (
            <div>
                <userContext.Provider value={value}>
                    <NavMenu />
                    <Container>
                        {this.props.children}
                    </Container>
                </userContext.Provider>
            </div>
        );
    }
}

src/components/NavMenu.js:

import { userContext } from '../userContext';
export class NavMenu extends Component {
    
  static displayName = NavMenu.name;
    componentDidMount() {
        let value = this.context;   
        /* perform a side-effect at mount using the value of MyContext */
    }
  constructor (props) {
    super(props);

    this.toggleNavbar = this.toggleNavbar.bind(this);
    this.state = {
        collapsed: true
    };
  }

  toggleNavbar () {
    this.setState({
      collapsed: !this.state.collapsed
    });
  }

    render() {
       
        if (true) {
            return (
                
                 
                <header>
                    <userContext.Consumer>

                        {({ value }) => {
                            console.log('test')
                            console.log(value);//------------>undefiened
                            console.log(this.context)
                        }}
                    </userContext.Consumer>
...

这里有什么我遗漏的吗

好像可以用。

我认为问题在于渲染道具的解构值:)

尝试:

<userContext.Consumer>
  {(value) => {
    console.log("test")
    console.log(value)
    console.log(this.context)
    return <b>HELLO</b>
  }}
</userContext.Consumer>

渲染道具参考:https://reactjs.org/docs/render-props.html