react context

栏目: 服务器 · 发布时间: 6年前

内容简介:1.安装并引入prop-types2.父组件中设置getChildContext()

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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

长尾理论

长尾理论

[美]克里斯·安德森 / 中信出版集团股份有限公司 / 2015-8-1 / 59.00元

互联网时代,大众市场不再一统天下,小众市场也可以呼风唤雨。 在《长尾理论》一书中,克里斯·安德森详细阐释了长尾的精华所在,指出商业和文化的未来不在于传统需求曲线上那个代表“畅销商品”的头部,而是那条代表“冷门商品”的经常被人遗忘的长尾。尽管我们仍然对热门商品着迷,但它们对消费者的吸引力已经大不如从前,因为市场已经大大分化。黄金电视节目的收视率几十年来一直在萎缩,若是在七八十年代,现在的一档最......一起来看看 《长尾理论》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具