开发者问题收集

上下文值未定义

2022-06-04
27

我是 React 的新手,正在努力解决一些本该很简单的问题。 当用户登录时,我想保存他们的上下文并在导航栏上显示/隐藏内容。 但是,当我将上下文传递给子项时,其值未定义。

可以在 此处 找到有关 Context 的指南。>

这是我的代码 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>
...

这里是否遗漏了什么

1个回答

看起来它可以工作。

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

尝试:

<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

D3Portillo
2022-06-04