美文网首页
react 中的context

react 中的context

作者: JamesSawyer | 来源:发表于2018-07-19 11:14 被阅读340次

context 表示上下文,将好像组件里面的全局变量一样,一般我们不使用这个属性,因为这个有可能损坏组件。指定 context 允许我们将变量从一个组件传递到另一个组件,而不需要一层一层的传递。推荐使用 props 或者 state来传递属性

使用方式

我们需要使用 prop-types 库来定义传递context的类型,另外:

  1. 父组件 中需要设置 childContextTypes(key-value 对象) 和 getChildContext()(返回context对象)
  2. 子组件 中需要设置 contextTypes 来获取 context, 并使用 this.context 来访问上下文对象

另外,上面的几个属性:

  • prop-types 是用来告诉 React我们的context的类型的
  • childContextTypes 不产生context, 只是定义context
  • getChildContext() 为了给context填充数据,我们需要调用这个函数

示例

父组件

import PropTypes from 'prop-types';

class Message extends Component {
    static propTypes = {
       users: PropTypes.array.isRequired,
       initialActiveChatIdx: PropTypes.number,
       messages: PropTypes.array.isRequired
    }

    // 在父组件中 定义上下文类型
    static childContextType = {
        users: PropTypes.array,
        userMap: PropTypes.object
    }

    // 在父组件中 给context填充数据
    getChildContext() {
        return { // 返回context对象
            users: this.getUsers(),
            userMap: this.getUserMap()
        }
    }

    getUsers = () => {
        // ... 获取数据
    }

    getUserMap = () => {
        // ... 获取数据
    }

    render() {
       return (
           <div>
                <ThreadList />
                <ChatWindow />
           </div>
       )
    }
}

子组件,获取context

class ThreadList extends Component {
    // 为了在子组件中抓取context, 我们需要告诉React我们想要访问context
    // 我们通过在子组件中定义 contextTypes 和 React交流
    static contextTypes = {
        users: PropTypes.array
    }

    render() {
        return (
            <div className={styles.threadList}>
                <ul className={styles.list}>
                    {this.context.users.map((user, idx) =>( // 通过 'this.context' 访问context中的数据
                        <UserListing 
                            onClick={this.props.onClick}
                            key={idx}
                            index={idx}
                            user={user}
                        />
                    ))}
                </ul>
            </div>
        )
    }
}



class ChatWindow extends Component {
    // 任何定义了contextTypes的子组件,我们都能够访问父组件中定义的数据
    // 而不必通过props来传递
    // context 数据通过 this.context 对象来获取
    static contextTypes = {
        userMap: PropType.object
    }
}

context 和 生命周期函数

如果加入了context, 下面生命周期函数将获取一个额外的参数

constructor(props, context)
componentWillReceiveProps(nextProps, nextContext)
shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate(nextProps, nextState, nextContext)
componentDidUpdate(prevProps, prevState, prevContext)

无状态函数也可以添加一个额外的参数

import PropTypes from 'prop-types';

const Button = ({children}, context) => 
    <Button style={{background: context.color}}>
        {children}
    </Button>

总结

在js中使用全局变量通常不是一个好的主意,context通常作为全局变量用于有限的场景中,比如 登录的用户,在产品阶段建议使用props,而不是使用 context。

由于组件的state和props可以改变,context也可以改变,每当父组件中的state或者props变化时,getChildContext() 都会被调用,context更新后,子组件也会重新渲染。但是如果子组件中使用 shouldComponentUpdate() 返回false,则子组件不会更新,会引发错误,所以慎用context。

相关文章

  • React中不常用的功能——Context

    React中不常用的功能——Context Context React源码版本16.8 基本用法 跨层级通信 Co...

  • React-深入探究Context(1)

    前言 React组件中的Context与Android中的Context类似,都可以理解为上下文。而React中的...

  • 2018-08-08

    React 高级指南 React 新版上下文(context) context ?答:上下文(Context) 提...

  • react中的context

    在React中,数据可以以流的形式自上而下的传递,每当你使用一个组件的时候,你可以看到组件的props属性会自上而...

  • react 中的context

    context 表示上下文,将好像组件里面的全局变量一样,一般我们不使用这个属性,因为这个有可能损坏组件。指定 c...

  • React 中的Context

    当我们想在组件树内传递props,并且不想让props流经树的每一层,context会让我们做到这一点。conte...

  • React中 的 Context

  • 关于react中的context

    一、context有什么用 当我们使用props进行组件中的数据传递时,假如祖先级组件的数据要传递至孙子级,这种情...

  • React中的Context理解

    今天看了下react官网的context,记录下学习过程和自己对context的理解。下面从为什么要用和怎么用两个...

  • React 中的 context(7)

    Context 作用:给整个组件树共享全局的数据 最适合的场景:杂乱无章的组件都需要同一些数据 如果单纯为了不层层...

网友评论

      本文标题:react 中的context

      本文链接:https://www.haomeiwen.com/subject/nqekjxtx.html