React Context
絕大多數(shù)應(yīng)用程序不需要使用 context.如果你想讓你的應(yīng)用更穩(wěn)定,別使用context。因為這是一個實驗性的API,在未來的React版本中可能會被更改。
一、如何使用
- 安裝并引入prop-types
- 父組件中設(shè)置getChildContext()
class A extends React.Component {
getClildContext () {
return {
info: 'test'
/** some code */
}
}
}
- 父子組件設(shè)置childContextTypes
import PropTypes from 'prop-types';
A.childContextTypes = {
info: PropTypes.string
}
- 子組件定義contextTypes獲取context中獲取并定義變量類型
B.contextTypes = {
info: PropTypes.string
}
- 子組件獲取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
}
二、使用要點
- 如果一個組件中定義了contextTypes,在下面的生命周期會獲得額外的參數(shù)
constructor(props, context);
componentWillReceiveProps(nextProps, nextContext);
shouldComponentUpdate(nextProps, nextState, nextContext);
componentWillDidUpdate(nextProps, nextState, nextContext);
componentDidUpdate(prevProps, PrevState, prevContext);
- 無狀態(tài)下引用context
import PropTypes from 'prop-types'
const C = ({ children }, context) => {
return (
<h2>{context.info}</h2>
)
}
C.contextTypes = {
info: PropTypes.string
}
- 千萬不要更新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
}
}
}
- PureComponent檢測不到context的改變