【问题标题】:Context data does not get passed into nested component: React+Typescript+ContextAPI上下文数据不会传递到嵌套组件中:React+Typescript+ContextAPI
【发布时间】:2019-06-18 11:25:15
【问题描述】:

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

组件A.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;

【问题讨论】:

    标签: reactjs typescript react-context


    【解决方案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);
      }
    }
    

    【讨论】:

    • Mihalyi,我想在渲染方法之外使用它
    • 子组件不能访问 this 而不必将它们作为 props 传递?
    • 我认为,不可能
    猜你喜欢
    • 1970-01-01
    • 2020-05-21
    • 2016-08-17
    • 2021-10-08
    • 2021-01-26
    • 1970-01-01
    • 2019-01-07
    • 2022-11-23
    • 2021-12-07
    相关资源
    最近更新 更多