简体   繁体   中英

React context return undefined

I am using React Context api to pass some states to different child components and it's returning undefined .

Parent component:

export const UserContext = React.createContext();
export class Provider extends Component {
  state = {
    editGroup: false,
  }
  render() {
    return (
      <UserContext.Provider value={{
        state: this.state
      }}>
        {this.props.children}
      </UserContext.Provider>
    )
  }
}

Child component:

import { UserContext } from './index';

return (
  <React.Fragment>
    <UserContext.Consumer>
      {(context) => (
        <p>im inside the consumer {console.log(context)}</p>
      )}
    </UserContext.Consumer>
  </React.Fragment>
);

This last console.log is returning as undefined , what am I doing wrong here ?

Also, make sure to pass context in the constructor if you override it!

    export default class Profile extends React.Component {
        static contextType = AuthContext;
        // make sure you pass the context along to super!
        constructor(props, context) {
            super(props, context);
            ...
        }
    }

In the child component change context to value (function parameter) in the Consumer section as thats is the prop passed to the Provider

<UserContext.Consumer>
  {(value) => ( 
    <p>im inside the consumer {console.log(value)}</p>
  )}
</UserContext.Consumer>

Full working sample

    import React, { Component } from 'react'
    const UserContext = React.createContext()

    const Main = () => (
      <Parent>
        <Child/>
      </Parent>
    )

    export default Main

    //***************************************/

    class Parent extends Component {

      state = {
        editGroup: false
      }

      render() {
        return (
          <UserContext.Provider value={{
            state: this.state
          }}>
            {this.props.children}
          </UserContext.Provider>
        )
      }
    }

    //***************************************/

    const Child = () => {
      return (
        <React.Fragment>
          <UserContext.Consumer>
            {(value) => (
              <p>Inside consumer {console.log(value)}</p>
            )}
          </UserContext.Consumer>
        </React.Fragment>
      );
    }

    //***************************************/

Output: state: {editGroup: false}

I ran into this issue myself recently. In my case, I was calling <MyContext.Consumer>{(context) => /* ... */}</MyContext.Consumer> from within a portal that was outside of my provider. Composition matters here!

<MyContext.Provider>
  /* ... tons and tons of code */

  <MyContext.Consumer>
    {(context) => {
      return (
        <Modal foo={context.foo} />  // gets rendered in a portal, far below the provider, but we've made a closure over it, so it's OK 
      )
    }}
  </MyContext.Consumer>
</MyContext.Provider>

You need to provide a context default value in createContext()

Like

export const UserContext = React.createContext('default');

Or

export const UserContext = React.createContext({ctx_key:"ctx_value"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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