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

相關文章
相關標籤/搜索