上下文数据不会传递到嵌套组件中:React+Typescript+ContextAPI

Context data does not get passed into nested component: React+Typescript+ContextAPI

我正在使用上下文 API 来避免跨组件钻孔。我有一个组件,它有两个弹出模式(组件)。当我试图在封闭组件数据中获取上下文数据时,但在模态中我不会获取。如果我再次传递这个上下文数据作为道具传递给这些模态,然后如果我获取这个道具访问器那么我就可以获取。我哪里错了?如果我没记错的话,这个上下文 API 不依赖于嵌套级别,有人可以帮我吗?

CacheContext.tsx

import React from "react";
const context = React.createContext(null);
export default context;

ContextProvider.tsx

import React, {Component} from "react";

import context from './CacheContext';

var TinyCache = require( 'tinycache' );
var cache = new TinyCache();

class ContextProvider extends Component {

    render() {
      return (
          <context.Provider value={cache}>
               {this.props.children}
          </context.Provider>
      );
    }
  }

  export default ContextProvider;

ComponentA.tsx

import * as React from "react";
import context from "../Utilities/CacheContext";

export default class ComponentA extends React.Component<{}, {}> {

  componentDidMount() {
    console.log(this.context) // I am able to the data here
  }

  render(){
    return(
        <Modal1/>   //if I pass this as context={this.context} then it works
        <Modal2/>
    )
  }
}
ComponentA.contextType=context;

Modal1.tsx

import * as React from "react";
import context from "../Utilities/CacheContext";

export default class Modal1 extends React.Component<{}, {}> {

   componentDidMount() {
    console.log(this.context) // I am unable able to the data here , If I use this.props.context and pass the context as props then I am able to get
  }

  render(){
    return(
        //some content
    )
  }
}
Modal1.contextType=context;

在新上下文 API ( https://reactjs.org/docs/context.html#api ) 中,您应该使用 context.Consumer 组件使用函数作为子组件:

<context.Consumer>
  {cache => console.log(cache)}
</context.Consumer>

如果你需要 componentDidMount 中的缓存,将缓存传递给 sub-component 像这样:

// render:
<context.Consumer>
  {cache => <SubComponent cache={cache}/>}
</context.Consumer>

// SubComponent:
class SubComponent {
  componentDidMount() {
    console.log(this.props.cache);
  }
}