在React v16.6中如何在新的CONTEXT API中获取多个静态上下文

Sak*_*oor 8 javascript reactjs

嗨,我正在尝试访问组件中的多个上下文,但是我仅从提供者那里获得了一个上下文值就获得了成功。有两个提供者ListContext和`MappingContext。我如何访问这样的上下文:

class TableData extends React.Component {
 static contextType = ListContext;
 static contextType = MappingContext;

 componentDidMount() {
   const data = this.context // it will have only one context from ListContext
  }
Run Code Online (Sandbox Code Playgroud)

我知道我可以在render()中使用多个提供程序,但我想访问上面的上下文。任何帮助将不胜感激。

谢谢

Rya*_*ell 8

一种解决方法是使用将两个上下文合并为一个包装器,然后导出包装器。有多种实现包装器的方法,但这是一种:

Contexts.js

import React from "react";

export const Context1 = React.createContext("1");
export const Context2 = React.createContext("2");
export const ContextCombined1And2 = React.createContext("3");
Run Code Online (Sandbox Code Playgroud)

ProvideCombinedContext.js

import React from "react";
import { Context1, Context2, ContextCombined1And2 } from "./Contexts";

// This is a reusable piece that could be used by any component that requires both contexts.
const ProvideCombinedContext = props => {
  return (
    <Context1.Consumer>
      {context1 => (
        <Context2.Consumer>
          {context2 => (
            <ContextCombined1And2.Provider value={{ context1, context2 }}>
              {props.children}
            </ContextCombined1And2.Provider>
          )}
        </Context2.Consumer>
      )}
    </Context1.Consumer>
  );
};
export default ProvideCombinedContext;
Run Code Online (Sandbox Code Playgroud)

Need2Contexts.js

import React from "react";
import { ContextCombined1And2 } from "./Contexts";
import ProvideCombinedContext from "./ProvideCombinedContext";

class Need2Contexts extends React.Component {
  static contextType = ContextCombined1And2;
  componentDidMount() {
    console.log("Context=" + JSON.stringify(this.context));
  }
  render() {
    return "this.context=" + JSON.stringify(this.context);
  }
}

const WrappedNeed2Contexts = props => {
  return (
    <ProvideCombinedContext>
      <Need2Contexts {...props} />
    </ProvideCombinedContext>
  );
};

export default WrappedNeed2Contexts;
Run Code Online (Sandbox Code Playgroud)

index.js

import React from "react";
import ReactDOM from "react-dom";
import { Context1, Context2 } from "./Contexts";
import Need2Contexts from "./Need2Contexts";

function App() {
  return (
    <div className="App">
      <Context1.Provider value="value1">
        <Context2.Provider value="value2">
          <Need2Contexts />
        </Context2.Provider>
      </Context1.Provider>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Run Code Online (Sandbox Code Playgroud)

您可以在操作中看到它并在此处进行操作:

编辑xv373l5ynz


keu*_*eul 5

这在React 上下文文档中有解释:

您只能使用此 API 订阅单个上下文。如果您需要阅读多篇文章,请参阅使用多个上下文

  • 是的。但是,如果我需要 componentDidMount 中的两个上下文,有什么解决方法? (2认同)