【发布时间】: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