【发布时间】:2020-10-09 08:59:04
【问题描述】:
我正在尝试了解 React 上下文 API,并且正在阅读官方文档。如果有人能对以下几点提出更多说明,我将不胜感激,因为官方文档没有明确说明。
- contextType 和 Consumer 方法有什么区别 使用 Provider 提供的值?在什么情况下我们应该 使用哪种方法?
- Provider 在基于类的组件中公开的值可以是 由使用 useContext 的反应钩子组件使用?我有同样的 设置,我最终将 useContext 转换为 Context.Consumer。
- 我有一个非常简单的设置,其中我有一个提供者类 基于暴露一些状态值的组件。提供者 只有一个子组件,它也是一个消费者。当我使用 Context.Consumer 在孩子中获取值,一切 按预期工作。但是当我在孩子们中使用 contextType 组件,我看到一个空对象。
ContextProvider.js
import React from "react";
import {ContextConsumer} from "./ContextConsumer";
export const TestContext = React.createContext({
count: 1,
incrCount: (count)=>{
console.log(`count value :- ${count}`)
}
});
export class ContextProvider extends React.Component {
incrCount = () => {
this.setState({
count: this.state.count + 1,
});
};
state = {
count: 5,
incrCount: this.incrCount,
};
render() {
return (
<TestContext.Provider value={this.state}>
<ContextConsumer />
</TestContext.Provider>
);
}
}
ContextConsumer.js
import React from "react";
import { TestContext } from "./ContextProvider";
export class ContextConsumer extends React.Component {
static contextType=TestContext
componentDidMount() {
const {count,incrCount}= this.context;
console.log(`count:- ${(count)}`)
console.log(`incrCount:- ${incrCount}`)
}
render() {
return (
<div>
**// BELOW CODE IS WORKING AS EXPECTED**
<TestContext.Consumer>
{({ count, incrCount }) => (
<button onClick={incrCount}>Count is {count}</button>
)}
</TestContext.Consumer>
</div>
);
}
}
App.js
import {ContextProvider} from "../../playground/ContextProvider";
const output = (
<Provider store={reduxStore}>
<ContextProvider />
</Provider>
);
ReactDOM.render(output, document.getElementById("root"));
【问题讨论】:
-
我认为您使用的是 v16.3.0 - v16.6.0 之间的 react 版本。 contextType 支持是在 16.6.0 中引入的。请查看此帖子stackoverflow.com/questions/49870098/…
-
是的,我目前在 16.13.1。但是上下文页面上没有与版本支持相关的信息reactjs.org/docs/context.html
-
@ryna,文档显示了最新版本的API,具体API介绍需要查看发行说明::reactjs.org/blog/2018/10/23/react-v-16-6.html
标签: reactjs react-context