react context

React Context

绝大多数应用程序不须要使用 context.若是你想让你的应用更稳定,别使用context。由于这是一个实验性的API,在将来的React版本中可能会被更改。javascript

1、如何使用

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

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

3.父子组件设置childContextTypesreact

import PropTypes from 'prop-types';

A.childContextTypes = {
  info: PropTypes.string
}

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

B.contextTypes = {
  info: PropTypes.string
}

5.子组件获取context变量code

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
}

2、使用要点

1.若是一个组件中定义了contextTypes,在下面的生命周期会得到额外的参数component

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是不会更新得。ip

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

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

4.PureComponent检测不到context的改变get

这是一个完整的demostring

相关文章
相关标签/搜索