react 共享数据流

层层传递Props

  • 单向数据流层层传递,繁琐不好管理。

Context

  • 什么是context?

context是react提供的组件通信api

  • context有什么用?

解决{组件.js}中多层级组件通信,参数层层传递的麻烦。

import React, { Component } from 'react';
import PropTypes  from 'prop-types';

const Inner1 = (props) => {
  return (
    <div style={{ border: '2px solid green' }}>
      <p>Inner1纯组件</p>
      <Inner2></Inner2>
    </div>
  )
}

const Inner2 = (props,context) => {
  return (
    <div style={{ border: '2px solid red' }}>
      <p>Inner2纯组件</p>
      <p>{context.color}</p>
    </div>
  )
}
Inner2.contextTypes = {
  color: PropTypes.string
}

class Top1 extends Component {
  getChildContext() {
    return { color: 'red' };
  }
  render() {
    return (
      <div>
        <Inner1></Inner1>
      </div>
    );
  }
}

Top1.childContextTypes = {
  color: PropTypes.string
}
export default Top1;
context 使用注意事项
  • 1-1 context 提供者(组件)中需定义getChildContext方法ruturn一个对象,对象中包含发布的信息。
  • 1-2context 提供者需定义 组件名.childContextTypes内容类型
  • 2-1访问者需定义 组件名.contextTypes内容类型
  • 2-2传参中添加context,以{context.属性}方式使用
    https://juejin.im/post/5a90e0545188257a63112977

createContext

引用官方文档:

The problem is, if a context value provided by component changes, descendants that use that value won’t update if an intermediate parent returns false from shouldComponentUpdate. This is totally out of control of the components using context, so there’s basically no way to reliably update the context.

简单说,就是如果context的值有更新时,没办法保证所有子节点一定能更新。

为什么?因为在老的Context中由上而下的“触发链”有可能被shouldComponentUpdate打断。
https://zhuanlan.zhihu.com/p/34038469

React.createContext() 此API会返回一个组件。

const Context = React.createContext();

使用这个组件中的静态Provider组件包裹子组件并发布消息。

<Context.Provider value={this.getContext()}>
    <LoginFormWith />
</Context.Provider>

子组件通过静态Consumer来消费信息。

<Context.Consumer>
    {(context) => (
        <div>{JSON.stringiy(context)}</div>
    )}
</Context.Consumer>

不过使用高阶函数来装载context更优雅
https://gitee.com/n3taway/tabs_component_packaging

posted @ 2019-04-01 17:17  hid3onbush  阅读(424)  评论(0编辑  收藏  举报