reactjs - 上下文数据不会传递到嵌套组件中: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;
组件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;
模态1.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 中的缓存,请将缓存传递给子组件,如下所示:
// render:
<context.Consumer>
{cache => <SubComponent cache={cache}/>}
</context.Consumer>
// SubComponent:
class SubComponent {
componentDidMount() {
console.log(this.props.cache);
}
}
推荐阅读
- c++ - clang-tidy - 忽略第三方标头代码
- raspberry-pi - Ublox NEO-M6 和 Raspberry Pi3
- android - 如何在 react-native-charts-wrapper 中的图表上设置点选择?
- python - 在 django 中集成“直接消息”功能的最佳方法是什么?
- git - 在 Git 中以交互方式变基时的“标签”是什么
- binary - 符号大小和二的恭维
- bash - jq如何获取对象中的最后一个条目
- botium-box - “botium-cli 仿真器控制台”失败并显示“错误:缺少功能‘CONTAINERMODE’或‘BOTIUMGRIDURL’”
- python - 从循环中的多个字符串中提取数字
- python - 根据列的列表条目中的值删除行