Reactjs Class.contextType和Context.Consumer之间的差异及工作示例

Reactjs Class.contextType和Context.Consumer之间的差异及工作示例,reactjs,react-context,Reactjs,React Context,我正在努力理解React上下文API,并且正在浏览官方文档。如果有人能就以下几点提供更多的信息,我将不胜感激,因为官方文件没有明确说明这一点 contextType和Consumer方法的区别是什么 是否使用提供者提供的值?在什么情况下我们应该 使用哪种方法 提供程序在基于类的组件中公开的值是否可以 由使用useContext的react钩子组件使用?我也吃了同样的 安装程序和我最终将useContext转换为Context.Consumer 我有一个非常简单的设置,其中有一个Provider类

我正在努力理解React上下文API,并且正在浏览官方文档。如果有人能就以下几点提供更多的信息,我将不胜感激,因为官方文件没有明确说明这一点

  • contextType和Consumer方法的区别是什么 是否使用提供者提供的值?在什么情况下我们应该 使用哪种方法
  • 提供程序在基于类的组件中公开的值是否可以 由使用useContext的react钩子组件使用?我也吃了同样的 安装程序和我最终将useContext转换为Context.Consumer
  • 我有一个非常简单的设置,其中有一个Provider类 基于组件,它公开了一些状态值。提供者 只有一个子组件,也是使用者。当我使用 消费者在子对象中获取值,一切 一切正常。但是当我在儿童中使用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>
        );
      }
    }
    
    从“React”导入React;
    从“/ContextConsumer”导入{ContextConsumer};
    export const TestContext=React.createContext({
    计数:1,
    incrCount:(计数)=>{
    log(`count value:-${count}`)
    }
    });
    导出类ContextProvider扩展React.Component{
    增量计数=()=>{
    这是我的国家({
    计数:this.state.count+1,
    });
    };
    状态={
    计数:5,
    incrCount:this.incrCount,
    };
    render(){
    返回(
    );
    }
    }
    
    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>
        );
      }
    }
    
    从“React”导入React;
    从“/ContextProvider”导入{TestContext};
    导出类ContextConsumer扩展React.Component{
    静态contextType=TestContext
    componentDidMount(){
    const{count,incrCount}=this.context;
    log(`count:-${(count)}`)
    log(`incrCount:-${incrCount}`)
    }
    render(){
    返回(
    **//下面的代码按预期工作**
    {({count,incrCount})=>(
    计数为{Count}
    )}
    );
    }
    }
    
    App.js

    import {ContextProvider}  from "../../playground/ContextProvider";
    
    const output = (
      <Provider store={reduxStore}>
        <ContextProvider />
      </Provider>
    );
    
    ReactDOM.render(output, document.getElementById("root"));
    
    import{ContextProvider}来自“../../playerd/ContextProvider”;
    常量输出=(
    );
    render(输出,document.getElementById(“根”);
    
    使用提供者提供的值的contextType和Consumer方法有什么区别?在什么情况下我们应该使用哪种方法?

    v16.6.0引入了
    静态contextType
    赋值,作为在渲染方法之外使用上下文的一种方式。使用者上下文和静态上下文之间的唯一区别是,使用contextType也可以在渲染方法之外使用上下文

    提供者在基于类的组件中公开的值是否可以由使用useContext的react钩子组件使用?

    是,
    useContext
    也可以使用提供程序中的上下文值。但是,您只能在功能组件内部使用
    useContext
    ,而不能在类组件内部使用,也可以在v16.8.0或支持挂钩的react之后使用

    p.S.您必须通过在消费者组件中导入提供者来确保一件事不会导致循环依赖性,反之亦然

  • 静态contextType和class.contextType
  • 使用上下文
  • 消费者
  • 它们之间的区别在于(1)在类和组件中使用
    useContext是一个钩子,最好的情况是我们可以在一个功能组件中多次使用这个钩子。(3)只能在jsx或render(return)中使用。(1)和(2)可以在return之外使用。

    我想您是在v16.3.0到v16.6.0之间使用react的版本。contextType支持是在16.6.0中引入的。请检查这篇文章是的,我现在在16.13.1。但是上下文页面@ryna上没有与版本支持相关的信息,文档显示了最新版本的API,您需要查看发行说明以了解特定的API介绍::我还提到了一篇在线文章,其中说使用消费者是消费提供者值的传统方式。这是真的吗?如果是这样的话,我们是否只使用contextType,但根据您的回复,我会不这么认为。“检索上下文值的传统方法是将子组件包装到使用者中。从此,您可以作为道具访问值道具。您可能仍然会看到这一点,但这更多的是访问上下文的传统方法。”@ryan上下文api已更改多次。最初,我们需要定义contextType,但对于提供程序,我们也需要使用ChildContextType。然后在v16.3中,react引入了提供者-消费者API,该API变得流行且简单,但有一个缺点,即使用自定义在呈现函数之外使用上下文,因此在v16.6.0中,他们对其进行了改进,并添加了静态contextType支持,以便我们也可以在其他生命周期中使用contextType。然后随着钩子的出现,他们引入了useContext来使用功能组件中的上下文。因此,虽然contextType是传统方式,但它也是使用上下文的最新方式。我做了更改,并将componentDidMount中的“console.log(this.context)”从render移到了componentDidMount中,但我仍然认为这些值未定义。我在这里遗漏了什么?可能是循环依赖。在单独的文件中而不是在提供程序中创建上下文