react context

React Context

絕大多數(shù)應(yīng)用程序不需要使用 context.如果你想讓你的應(yīng)用更穩(wěn)定,別使用context。因為這是一個實驗性的API,在未來的React版本中可能會被更改。

一、如何使用

  1. 安裝并引入prop-types
  2. 父組件中設(shè)置getChildContext()
class A extends React.Component {
  getClildContext () {
    return {
      info: 'test'
      /** some code */
    }
  }
}
  1. 父子組件設(shè)置childContextTypes
import PropTypes from 'prop-types';

A.childContextTypes = {
  info: PropTypes.string
}
  1. 子組件定義contextTypes獲取context中獲取并定義變量類型
B.contextTypes = {
  info: PropTypes.string
}
  1. 子組件獲取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,在下面的生命周期會獲得額外的參數(shù)
constructor(props, context);
componentWillReceiveProps(nextProps, nextContext);
shouldComponentUpdate(nextProps, nextState, nextContext);
componentWillDidUpdate(nextProps, nextState, nextContext);
componentDidUpdate(prevProps, PrevState, prevContext);
  1. 無狀態(tài)下引用context
import PropTypes from 'prop-types'

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

C.contextTypes = {
  info: PropTypes.string
}
  1. 千萬不要更新context,可以通過與state綁定更新context,有風(fēng)險的如果中間父組件通過shouldComponentUpdate返回false,那么接下來的組件中的context是不會更新得。
class A extends React.PureComponent {
  constructor () {
    super();
    this.state = {
      info: 'test'
    }
  }

  getChildContext () {
    return {
      info: this.state.info
    }
  }
}
  1. PureComponent檢測不到context的改變

這是一個完整的demo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容