react中对于context的理解

一、context旧版的基本使用
1、context的理解
当不想在组件树中通过逐层传递props或state的方式来传递数据时,可使用context来实现跨层级的组件数据传递。
2、context的使用
在使用context时需要用到两个组件,一个是context生产者Provider,通常是一个父节点,另外一个时context的消费者Consumer,通常是一个或多个子节点。所以context的使用基于生产者消费者模式。
对于父组件(即生产者),需要通过一个静态属性(static)childContextTypes声明提供给子组件的context对象的属性,并实现一个实例getChildContext方法,返回一个代表context的对象。
(1)getChildContext:根组件中声明,是一个函数,返回一个对象,就是context
(2)childContextTypes:根组件中声明,指定context的结构类型,若不指定会产生错误
(3)contextTypes:子孙组件中声明,指定要接收的context的结构类型,可以只是context的一部分结构。若没有定义,则context将会是一个空对象。
(4)this.context:在子孙组件中通过此来获取上下文。
3、context在如下的生命周期钩子中可以使用
constructor(props, context)
componentWillReceiveProps(nextProps, nextContext)

shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate(nextProps, nextState, nextContext)

componentDidUpdate(prevProps, prevState, prevContext)
4、context的局限性
(1)在组件树中,如果中间某一个组件 ShouldComponentUpdate return false 了,会阻 碍 context 的正常传值,导致子组件无法获取更新。
(2)组件本身 extends React.PureComponent 也会阻碍 context 的更新。
二、context新版的基本使用
1、全局定义context对象:
创建一个globalContext.js文件:
import React from "react";
const GlobalContext = React.createContext();
export default GlobalContext;
2、根组件引入GlobalContext,并使用GlobalContext.Provider(生产者):
import One from "./components/one";
import GlobalContext from "./globalContext";

<GlobalContext.Provider
    value={{
        name:"zhangsan",
        age:19
        }}
>
    <One/>
</GlobalContext.Provider>
3、组件引入GlobalContext并调用context,使用GlobalContext.Consumer:
<GlobalContext.Consumer>
    {
        context => {
            console.log(context)
            return (
                <div>
                    <h2>{context.name}</h2> 
                    <h2>{context.age}</h2>
                </div>
            )
        }
    }
</GlobalContext.Consumer>
原文地址:https://www.cnblogs.com/Leslie-Cheung1584304774/p/10734634.html