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

IT技术 javascript reactjs
2021-04-23 02:35:07

嗨,我正在尝试访问一个组件中的多个上下文,但我仅通过提供程序提供的一个上下文值就获得了成功。有两个提供者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
  }

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

谢谢

2个回答

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

Contexts.js

import React from "react";

export const Context1 = React.createContext("1");
export const Context2 = React.createContext("2");
export const ContextCombined1And2 = React.createContext("3");

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;

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;

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);

您可以在此处查看并使用它:

编辑 xv373l5ynz

感谢详细的编码。很容易理解:)
2021-05-23 02:35:07
对于类组件中的动态多重上下文,请参考linkedin.com/pulse/...
2021-06-11 02:35:07

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

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

是的。但是,如果我需要 componentDidMount 中的两个上下文,有什么解决方法?
2021-06-14 02:35:07