zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    单页面应用和多页面应用区别及优缺点
    Vue中双向数据绑定是如何实现的?
    vue组件中data为什么必须是一个函数?
    $nextTick的使用
    分别简述computed和watch的使用场景
    webpack结合postcss-loader实现css样式浏览器兼容前缀的添加
    KeyError:‘uid' Python常见错误
    GO语言学习之 跨平台编译
    图表动态选择+图表联动
    软件需求与分析大作业进度八
  • 原文地址:https://www.cnblogs.com/hideonbush/p/10637601.html
Copyright © 2011-2022 走看看