当前位置: 首页 > news >正文

React 状态管理 - Context API 前世今生(上)旧版v16.3前

目录

扩展学习资料

Context api before React v16.3

Context

实战使用-Context

Context VS Props

Context

Props

Context的缺陷


New Context API 的实践

扩展学习资料

名称

链接

备注

new context api

https://reactjs.org/docs/context.html

英文

old context api

https://5abc31d8be40f1556f06c4be--reactjs.netlify.app/docs/context.html

context api 问题

https://medium.com/@gobindathakur/problems-with-previous-react-context-api-317b247d78d4

英文

Context api before React v16.3

官方说:功能强大,但是不推荐使用

Context

Context: React 的‘上下文’,贯穿了整个React,不需要层层传递。

  • childContextTypes 父级组件定义,声明Context对象属性。【定义属性】
  • getChildContext 父级组件定义,返回Context对象,方法名是约定的。【属性赋值】
  • contextTypes 在任意层级的子级组件中定义,就可以在子级组件使用context。【子级使用】

实战使用-Context

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CustomButton from './components/customButton';
// 父组件
export default class Home extends Component {// 定义类型static childContextTypes = {color: PropTypes.string,    }constructor(props) {super(props);this.state = {color: '#28a745',       };    }// 属性赋值getChildContext() {// 动态值stateconst { color } = this.state;return {color,        }   }render() {return (<div><CustomButton>React Context Demo</CustomButton></div>);}
}
// 子组件
export default function CustomButton(props, context) {const { color } = context;const { children } = props;return (<button type="button" style={{ color }}>{ children }</button>    );
}
// 定义context类型
CustomButton.contextTypes = {color: PropTypes.string,
}
CustomButton.propTypes = {children: PropTypes.string,
};
CustomButton.defaultProps = {children: '默认文案',
};

Context VS Props

Context

  • 父级(根节点)与应用节点都需要强制类型声明,关键字不一样。
  • 全局上下文,贯穿了整个应用。
Props

  • 应用节点需要类型声明,非强制。
  • 只能进行逐级传递,一旦中间断掉,就会传递失败。

Context的缺陷

  • setState()时,getChildContext()也会触发。父级组件的shouldComponentUpdate返回false,就会不执行getChildContext(),引起更新失败。导致子组件接收到的context还是老的,破坏了传递流程。
  • PureComponent或者自定义的优化可能接收不到Context的更新。
http://www.lryc.cn/news/189246.html

相关文章:

  • 微服务、SOA 和 API 之间的区别
  • python打印正反直角三角形
  • ubuntu安装Miniconda并举例使用
  • 如何保护您的数据免受.360勒索病毒的感染
  • 2024计算机保研--哈工大、中山、国防科大
  • Hadoop分布式集群搭建教程
  • 学习函数式编程、可变参数及 defer - GO语言从入门到实战
  • Linux 文件链接
  • 1.go web之gin框架
  • 工程物料管理信息化建设(十二)——关于工程物料管理系统最后的思考
  • 什么是API网关?——驱动数字化转型的“隐形冠军”
  • Java 序列化和反序列化为什么要实现 Serializable 接口?
  • 【【萌新的SOC学习之GPIO学习 水】】
  • 10-Node.js入门
  • Redis 的过期键 | Navicat 技术干货
  • IDC服务器商是如何保护服务器的数据安全
  • c++中什么时候用double?
  • TCP/IP(四)TCP的连接管理(一)三次握手
  • bash上下键选择选项demo脚本
  • cf 1886A
  • Spring5应用之事务属性
  • C# 搭建一个简单的WebApi项目23.10.10
  • VGG卷积神经网络实现Cifar10图片分类-Pytorch实战
  • CentOS 7文件系统中的软链接和硬链接
  • 【AI】深度学习——前馈神经网络——全连接前馈神经网络
  • 超简单的视频截取方法,迅速提取所需片段!
  • ArcGIS/GeoScene脚本:基于粒子群优化的支持向量机回归模型
  • vue3组件的通信方式
  • Qt QPair
  • K8S云计算系列-(3)