繁体   English   中英

React Context API - 一个提供者,多个消费者

[英]React Context API - One provider, multiple consumers

我正在尝试习惯 React 的 Context API 功能,并且我正在尝试做的是在 2 个其他组件中使用一个组件中提供的上下文。 不幸的是,试图访问第二上下文消费者的上下文时,上下文undefined 我该如何解决这个问题?

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;

Context 仅对其后代可用

上下文共享的工作方式是所有需要访问上下文数据的组件都必须包装在单个提供程序中。

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

在上面的代码片段中, App是最顶层的组件。 层次结构是:

App
|-- Home
|-- About

现在HomeAbout可以访问 Context 中的值。


在您的代码中, Person.js可能没有呈现为<AuthContext.Provider>的后代,因此它无法访问它。 换句话说,提供者应该“包围”消费者。 从文档

Context 旨在共享可被视为“全局”的 React 组件树的数据 [...]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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