简体   繁体   中英

React Context API - One provider, multiple consumers

I am trying to get used to the Context API functionality of React, and what I'm trying to do is to consume the context provided in one component in 2 other components. Unfortunately, when trying to access the context in the second context consumer, the value of the context is undefined . How can I solve this?

Provider (snippet) :

const [loginState, changeLoginState] = useState({
    isAuthenticated: false,
    login: () => {}
  });

  const loginHandler = () => {
    let newState = {...loginState};
    newState.isAuthenticated = true;
    changeLoginState(newState);
  };

  return (
    <div className={CSSmodule.App}>

    <AuthContext.Provider value = { {
      isAuthenticated: loginState.isAuthenticated,
      login: loginHandler
    } }>

      <Cockpit 
        showValuesState = {showValuesState}
        showContent = {showContent}
        personsStateLength = {personsState.length}/>

    </AuthContext.Provider>
);

Consumer 1 (works) :

<AuthContext.Consumer>
         {
              (context) => {
                    console.log("[Cockpit.js]", context);   
                        return (
                            <button
                                onClick = {context.login}>
                                     Login
                            </button>
                        ); 
               }
         }
</AuthContext.Consumer>

Consumer 2 (context value is undefined) :

<AuthContext.Consumer>
     {
            (context) => {
                console.log("[from Person.js]", context);
                if(context.isAuthenticated)
                      return (<p>Authenticated!</p>);
             }
     }
</AuthContext.Consumer>

Imported AuthContext component from context.js :

import React from "react";

const context = React.createContext();

export default context;

The Context is only available to its descendants

The way context sharing works is that all your components which needs to access the context data must be wrapped within a single provider.

<Context.Provider value={}>
    <App/>
</Context.Provider>

In the above snippet, App is the top most component. The hierarchy is:

App
|-- Home
|-- About

Now Home and About can access values from the Context.


In your code, Person.js is probably not rendered as a descendant of the <AuthContext.Provider> , so it can't get access to it. In other words, the provider should "enclose" the consumers. From the docs :

Context is designed to share data that can be considered “global” for a tree of React components [...]

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