Class.contextType 和 Context.Consumer 之间的区别与工作示例 [英] Difference Between Class.contextType and Context.Consumer with working example

查看:79
本文介绍了Class.contextType 和 Context.Consumer 之间的区别与工作示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 React 上下文 API,并且正在阅读官方文档.如果官方文档没有明确说明以下几点,我将不胜感激.

  1. contextType 和 Consumer 方法有什么区别消费 Provider 提供的值?在什么情况下我们应该使用哪种方法?
  2. Provider 在基于类的组件中公开的值可以是由使用useContext的反应钩子组件使用?我有同样的设置,我最终将 useContext 转换为 Context.Consumer.
  3. 我有一个非常简单的设置,其中有一个 Provider 类基于组件,它暴露了一些状态值.提供者只有一个子组件也是消费者.当我使用Context.Consumer 在子代中获取值,一切按预期工作.但是当我在孩子中使用 contextType 时组件,我看到一个空对象.

ContextProvider.js

从react"导入React;从./ContextConsumer"导入{ContextConsumer};export const TestContext = React.createContext({计数:1,incrCount:(计数)=>{console.log(`计数值 :- ${count}`)}});导出类 ContextProvider 扩展 React.Component {incrCount = () =>{this.setState({计数:this.state.count + 1,});};状态 = {数:5,incrCount: this.incrCount,};使成为() {返回 (<TestContext.Provider value={this.state}><上下文消费者/></TestContext.Provider>);}}

ContextConsumer.js

从react"导入React;import { TestContext } from "./ContextProvider";导出类 ContextConsumer 扩展 React.Component {静态上下文类型=测试上下文componentDidMount() {const {count,incrCount}= this.context;console.log(`count:- ${(count)}`)console.log(`incrCount:- ${incrCount}`)}使成为() {返回 (<div>**//下面的代码按预期工作**<TestContext.Consumer>{({ count, incrCount }) =>(<button onClick={incrCount}>Count 是 {count}</button>)}</TestContext.Consumer>

);}}

App.js

从../../playground/ContextProvider"导入{ContextProvider};常量输出 = (<提供者商店={reduxStore}><ContextProvider/></提供者>);ReactDOM.render(output, document.getElementById("root"));

解决方案

contextType 和 Consumer 方法在消费 Provider 提供的值时有什么区别?在什么情况下我们应该使用哪种方法?

static contextType 赋值是在 v16.6.0 中引入的,作为在渲染方法之外使用上下文的一种方式.消费者和静态上下文之间的唯一区别是,使用 contextType 也允许您在渲染方法之外使用上下文

Provider 在基于类的组件中公开的值可以被使用 useContext 的 React 钩子组件使用吗?

是的,来自 Provider 的上下文值也可以被 useContext 使用.但是,您只能在功能组件中使用 useContext 而不能在类组件中使用,并且在 v16.8.0 或支持钩子的 react 之后也可以使用

P.S. 您必须确保通过在使用者组件中导入提供者以及其他方式不会导致循环依赖的一件事

I am trying to understand the React context API and was going through the official docs. I will appreciate if someone can throw some more light on the following points as the official doc does not address it clearly.

  1. What is the difference in contextType and Consumer methods to consume the values provided by Provider? In what situation we should use which method?
  2. Can the value exposed by Provider in a class based component, be used by a react hook component using useContext? I had the same setup and i ended up converting the useContext to Context.Consumer.
  3. I have a very straightforward setup in which i have a Provider Class based component which is exposing some state values. The Provider has only one children component which is also a consumer. When i use Context.Consumer in the children to fetch the values, everything works as expected. But when i use contextType in the children component, i see an empty object.

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"));

解决方案

What is the difference in contextType and Consumer methods to consume the values provided by Provider? In what situation we should use which method?

The static contextType assignment was introduced in v16.6.0 as a way to use context outside of render method. The only difference between Consumer and static context is the fact that using contextType allows you use context outside of render method too

Can the value exposed by Provider in a class based component, be used by a react hook component using useContext?

Yes the context value from Provider can be used by useContext too. However you can only make use of useContext inside a functional component and not a class component and also after v16.8.0 or react which supports hooks

P.S. You must ensure one thing that you are not causing a circular dependency by importing provider in consumer component and also the other way around

这篇关于Class.contextType 和 Context.Consumer 之间的区别与工作示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆