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

时间:2019-06-18 11:25:15

标签: reactjs typescript react-context

我正在使用上下文 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;

1 个答案:

答案 0 :(得分:1)

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

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

如果您需要componentDidMount中的缓存,请将缓存传递给子组件,如下所示:

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

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