react-context

18次阅读

共计 1522 个字符,预计需要花费 4 分钟才能阅读完成。

React Context

绝大多数应用程序不需要使用 context. 如果你想让你的应用更稳定,别使用 context。因为这是一个实验性的 API,在未来的 React 版本中可能会被更改。

一、如何使用

1. 安装并引入 prop-types
2. 父组件中设置 getChildContext()

class A extends React.Component {getClildContext () {
    return {
      info: 'test'
      /** some code */
    }
  }
}

3. 父子组件设置 childContextTypes

import PropTypes from 'prop-types';

A.childContextTypes = {info: PropTypes.string}

4. 子组件定义 contextTypes 获取 context 中获取并定义变量类型

B.contextTypes = {info: PropTypes.string}

5. 子组件获取 context 变量

class B extends React.Component {render () {return <div>{this.context.info}</div>
  }
}

完整 demo

import PropTypes from 'prop-types';
import React, {Component} from 'react';

class A extends React.Component {getClildContext () {
    return {
      info: 'test'
      /** some code */
    }
  }

  render () {return <B />}
}
A.childContextTypes = {info: PropTypes.string}

class B extends React.Component {render () {return <div>{this.context.info}</div>
  }
}
B.contextTypes = {info: PropTypes.string}

二、使用要点

1. 如果一个组件中定义了 contextTypes, 在下面的生命周期会获得额外的参数

constructor(props, context);
componentWillReceiveProps(nextProps, nextContext);
shouldComponentUpdate(nextProps, nextState, nextContext);
componentWillDidUpdate(nextProps, nextState, nextContext);
componentDidUpdate(prevProps, PrevState, prevContext);

2. 无状态下引用 context

import PropTypes from 'prop-types'

const C = ({children}, context) => {
  return (<h2>{context.info}</h2>
  )
}

C.contextTypes = {info: PropTypes.string}

3. 千万不要更新 context,可以通过与 state 绑定更新 context,有风险的如果中间父组件通过 shouldComponentUpdate 返回 false, 那么接下来的组件中的 context 是不会更新得。

class A extends React.PureComponent {constructor () {super();
    this.state = {info: 'test'}
  }

  getChildContext () {
    return {info: this.state.info}
  }
}

4.PureComponent 检测不到 context 的改变

这是一个完整的 demo

正文完
 0