react中对于context的理解

1、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 的更新。
2、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>
相关文章
相关标签/搜索