编写高性能React组件-传值篇
很多人在写React组件的时候没有太在意React组件的性能,使得React做了很多不必要的render,现在我就说说该怎么来编写搞性能的React组件。
首先我们来看一下下面两个组件
import React, {PureComponent,Component} from "react"
import PropTypes from "prop-types"
class A extends Component {
constructor(props){
super(props);
}
componentDidUpdate() {
console.log("componentDidUpdate")
}
render (){
return (
<div />
)
}
}
class Test extends Component {
constructor(props) {
super(props);
this.state={
value:0
};
}
static propTypes = {};
static defaultProps = {};
componentDidMount() {
setTimeout(()=>{
this.setState({value:this.state.value+1})
},100);
}
render() {
return (
<A />
)
}
}
运行结果:
Test state change.
A componentDidUpdate
我们发现上面代码中只要执行了Test组件的中的setState,无论Test组件里面包含的子组件A是否需要这个state里面的值,A componentDidUpdate始终会输出
试想下如果子组件下面还有很多子组件,组件又嵌套子组件,子子孙孙无穷尽也,这是不是个很可怕的性能消耗?
当然,针对这样的一个问题最初的解决方案是通过shouldComponentUpdate方法做判断更新,我们来改写下组件A
class A extends Component {
constructor(props){
super(props);
}
static propTypes = {
value:PropTypes.number
};
static defaultProps = {
value:0
};
shouldComponentUpdate(nextProps, nextState) {
return nextProps.value !== this.props.value;
}
componentDidUpdate() {
console.log("A componentDidUpdate");
}
render (){
return (
<div />
)
}
}
这里增加了shouldComponentUpdate方法来对传入的value属性进行对面,虽然这里没有传,但是不影响,运行结果:
Test state change.
好了,这次结果就是我们所需要的了,但是如果每一个组件都这样做一次判断是否太过于麻烦?
那么React 15.3.1版本中增加了 PureComponent ,我们来改写一下A组件
class A extends PureComponent {
constructor(props){
super(props);
}
static propTypes = {
value:PropTypes.number
};
static defaultProps = {
value:0
};
componentDidUpdate() {
console.log("A componentDidUpdate");
}
render (){
return (
<div />
)
}
}
这次我们去掉了shouldComponentUpdate,继承基类我们改成了PureComponent,输出结果:
Test state change.
很好,达到了我们想要的效果,而且代码量也减小了,但是真的可以做到完全的防止组件无畏的render吗?让我们来看看PureComponent的实现原理
最重要的代码在下面的文件里面,当然这个是React 16.2.0版本的引用
/node_modules/fbjs/libs/shallowEqual
大致的比较步骤是:
1.比较两个Obj对象是否完全相等用===判断
2.判断两个Obj的键数量是否一致
3.判断具体的每个值是否一致
不过你们发现没有,他只是比对了第一层次的结构,如果对于再多层级的结构的话就会有很大的问题
来让我们修改源代码再来尝试:
class A extends PureComponent {
constructor(props){
super(props);
}
static propTypes = {
value:PropTypes.number,
obj:PropTypes.object
};
static defaultProps = {
value:0,
obj:{}
};
componentDidUpdate() {
console.log("A componentDidUpdate");
}
render (){
return (
<div />
)
}
}
class Test extends Component {
constructor(props) {
super(props);
this.state={
value:0,
obj:{a:{b:123}}
};
}
static propTypes = {};
static defaultProps = {};
componentDidMount() {
setTimeout(()=>{
console.log("Test state change.");
let {obj,value} = this.state;
//这里修改了里面a.b的值
obj.a.b=456;
this.setState({
value:value+1,
obj:obj
})
},100);
}
render() {
let {
state
} = this;
let {
value,
obj
} = state;
return (
<A obj={obj} />
)
}
}
输出结果:
Test state change.
这里不可思议吧!这也是很多人对引用类型理解理解不深入所造成的,对于引用类型来说可能出现引用变了但是值没有变,值变了但是引用没有变,当然这里就暂时不去讨论js的数据可变性问题,要不然又是一大堆,大家可自行百度这些
那么怎么样做才能真正的处理这样的问题呢?我先增加一个基类:
import React ,{Component} from 'react';
import {is} from 'immutable';
class BaseComponent extends Component {
constructor(props, context, updater) {
super(props, context, updater);
}
shouldComponentUpdate(nextProps, nextState) {
const thisProps = this.props || {};
const thisState = this.state || {};
nextState = nextState || {};
nextProps = nextProps || {};
if (Object.keys(thisProps).length !== Object.keys(nextProps).length ||
Object.keys(thisState).length !== Object.keys(nextState).length) {
return true;
}
for (const key in nextProps) {
if (!is(thisProps[key], nextProps[key])) {
return true;
}
}
for (const key in nextState) {
if (!is(thisState[key], nextState[key])) {
return true;
}
}
return false;
}
}
export default BaseComponent
大家可能看到了一个新的东西Immutable,不了解的可以自行百度或者 Immutable 常用API简介 , Immutable 详解
我们来改写之前的代码:
import React, {PureComponent,Component} from "react"
import PropTypes from "prop-types"
import Immutable from "immutable"
import BaseComponent from "./BaseComponent"
class A extends BaseComponent {
constructor(props){
super(props);
}
static propTypes = {
value:PropTypes.number,
obj:PropTypes.object
};
static defaultProps = {
value:0,
obj:{}
};
componentDidUpdate() {
console.log("A componentDidUpdate");
}
render (){
return (
<div />
)
}
}
class Test extends Component {
constructor(props) {
super(props);
this.state={
value:0,
obj:Immutable.fromJS({a:{b:123}})
};
}
static propTypes = {};
static defaultProps = {};
componentDidMount() {
setTimeout(()=>{
console.log("Test state change.");
let {obj,value} = this.state;
//注意,写法不一样了
obj = obj.setIn(["a","b"],456);
this.setState({
value:value+1,
obj:obj
})
},100);
}
render() {
let {
state
} = this;
let {
value,
obj
} = state;
return (
<A obj={obj} />
)
}
}
执行结果:
Test state change.
A componentDidUpdate
这样也达到了我们想要的效果
当然,还有一种比较粗暴的办法就是直接把obj换成一个新的对象也同样可以达到跟新的效果,但是可控性不大,而且操作不当的话也会导致过多的render,所以还是推荐使用immutable对结构层级比较深的props进行管理
上面的一大堆主要是讲述了对基本类型以及Object(Array 其实也是Object,这里就不单独写示例了)类型传值的优化,下面我们来讲述关于function的传值
function其实也是Object,但是纯的function比较特么,他没有键值对,无法通过上面提供的方法去比对两个function是否一致,只有通过引用去比较,所以改不改引用成为了关键
改了下代码:
import React, {PureComponent,Component} from "react"
import PropTypes from "prop-types"
import Immutable from "immutable"
import BaseComponent from "./BaseComponent"
class A extends BaseComponent {
constructor(props){
super(props);
}
static propTypes = {
value:PropTypes.number,
obj:PropTypes.object,
onClick:PropTypes.func
};
static defaultProps = {
value:0,
obj:{}
};
componentDidUpdate() {
console.log("A componentDidUpdate");
}
render (){
let {
onClick
} = this.props;
return (
<div onClick={onClick} >
你来点击试试!!!
</div>
)
}
}
class Test extends Component {
constructor(props) {
super(props);
this.state={
value:0,
};
}
static propTypes = {};
static defaultProps = {};
componentDidMount() {
setTimeout(()=>{
console.log("Test state change.");
let {value} = this.state;
this.setState({
value:value+1,
})
},100);
}
onClick(){
alert("你点击了一下!")
}
render() {
let {
state
} = this;
let {
value,
obj
} = state;
return (
<A
onClick={()=>this.onClick()}
/>
)
}
}
运行结果:
Test state change.
A componentDidUpdate
我们setState以后控件A也跟着更新了,而且还用了我们上面所用到的BaseComponent,难道是BaseComponent有问题?其实并不是,看Test组件里面A的onClick的赋值,这是一个匿名函数,这就意味着其实每次传入的值都是一个新的引用,必然会导致A的更新,我们这样干:
class Test extends Component {
constructor(props) {
super(props);
this.state={
value:0,
};
}
static propTypes = {};
static defaultProps = {};
componentDidMount() {
setTimeout(()=>{
console.log("Test state change.");
let {value} = this.state;
this.setState({
value:value+1,
})
},100);
}
onClick=()=>{
alert("你点击了一下!")
};
render() {
let {
state
} = this;
let {
value
} = state;
return (
<A
onClick={this.onClick}
/>
)
}
}
输出结果:
Test state change.
嗯,达到我们想要的效果了,完美!
不过我还是发现有个问题,如果我在事件或者回调中需要传值就痛苦了,所以在写每个组件的时候,如果有事件调用或者回调的话最好定义一个接收任何类型的属性,最终的代码类似下面这样
import React, {PureComponent, Component} from "react"
import PropTypes from "prop-types"
import Immutable from "immutable"
import BaseComponent from "./BaseComponent"
class A extends BaseComponent {
constructor(props) {
super(props);
}
static propTypes = {
value: PropTypes.number,
obj: PropTypes.object,
onClick: PropTypes.func,
//增加data传值,接收任何类型的参数
data: PropTypes.any
};
static defaultProps = {
value: 0,
obj: {},
data: ""
};
componentDidUpdate() {
console.log("A componentDidUpdate");
}
//这里也进行了一些修改
onClick = () => {
let {
onClick,
data
} = this.props;
onClick && onClick(data);
};
render() {
return (
<div onClick={this.onClick}>
你来点击试试!!!
</div>
)
}
}
class Test extends Component {
constructor(props) {
super(props);
this.state = {
value: 0,
};
}
static propTypes = {};
static defaultProps = {};
componentDidMount() {
setTimeout(() => {
console.log("Test state change.");
let {value} = this.state;
this.setState({
value: value + 1,
})
}, 100);
}
onClick = () => {
alert("你点击了一下!")
};
render() {
let {
state
} = this;
let {
value
} = state;
return (
<A
onClick={this.onClick}
data={{message: "任何我想传的东西"}}
/>
)
}
}
总结一下:
1.编写React组件的时候使用自定义组件基类作为其他组件的继承类
2.使用Immutable管理复杂的引用类型状态
3.传入function类型的时候要传带引用的,并且注意预留data参数用于返回其他数据
如果大家有什么意见或者建议都可以在评论里面提哦
编写高性能React组件-传值篇的更多相关文章
- React组件传值方式总结
1. 子组件向父组件传值 父组件Header: import Nav from 'Nav.js'; class Header extends React.Component { constructor ...
- 深入理解React组件传值(组合和继承)
在文章之前,先把这句话读三遍 Props 和组合为你提供了清晰而安全地定制组件外观和行为的灵活方式.注意:组件可以接受任意 props,包括基本数据类型,React 元素以及函数. 来源于React中 ...
- React 组件传值 父传递儿子
10===> 传递参数 import React from "react" //一定要导入React // 函数类型去创建组件 export function Web1(pr ...
- React组件传值
React的单向数据流与组件间的沟通. 首先,我认为使用React的最大好处在于:功能组件化,遵守前端可维护的原则. 先介绍单向数据流吧. React单向数据流: React是单向数据流,数据主要从父 ...
- 我们编写 React 组件的最佳实践
刚接触 React 的时候,在一个又一个的教程上面看到很多种编写组件的方法,尽管那时候 React 框架已经相当成熟,但是并没有一个固定的规则去规范我们去写代码. 在过去的一年里,我们在不断的完善我们 ...
- 编写React组件的最佳实践
此文翻译自这里. 当我刚开始写React的时候,我看过很多写组件的方法.一百篇教程就有一百种写法.虽然React本身已经成熟了,但是如何使用它似乎还没有一个"正确"的方法.所以我( ...
- React子组件与父组件传值
一 子组件向父组件传值 //子组件var Child = React.createClass({ render: function(){ return ( <div> 请输入邮箱:< ...
- React学习笔记(三) 组件传值
组件嵌套后,父组件怎么向子组件发送数据呢? 答案是: this.props <script type="text/babel"> var MyFirst = React ...
- 使用React.cloneElement()给子组件传值
React提供了一个克隆组件的API: React.cloneElement( element, [props], [...child] ) 可以利用该方法,给子组件传值,使用如下: class Pa ...
随机推荐
- python 函数学习之sys.argv[1]
一.sys 模块 sys是Python的一个「标准库」,也就是官方出的「模块」,是「System」的简写,封装了一些系统的信息和接口. 官方的文档参考:https://docs.python.org/ ...
- LeetCode Count and Say 数数字
class Solution { public: string countAndSay(int n) { ) "; "; int i,t,count; char c='*'; ;i ...
- linux 命令——39 grep (转)
Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来.grep全称是Global Regular Expression Print,表示全局正则表达 ...
- libav(ffmpeg)简明教程(2)
距离上一次教程又过去了将近一个多月,相信大家已经都将我上节课所说的东西所完全消化掉了. 这节课就来点轻松的,说说libav的命令使用吧. 注:遇到不懂的或者本文没有提到的可以用例如命令后加 --hel ...
- js中(break,continue,return)的区别
break 一般用于跳出整个循环(for,while) continue 跳出本次循环,进入下一次循环 return 只能出现在函数体内,一旦执行return,后面的代码将不会执行,经常用retur ...
- Web前端学习流程
- Java代码工具箱之超出游标最大数
1. Java大量写入oracle时容易出现此错.经过此错,也触动自己要深刻理解 java 的 prepareStatement 等对象,及数据库的连接与释放. 2. 原因:经常会出现在 for 循环 ...
- Eclipse 发布 JAR
明确要生成何种类型 jar 生成工具 jar,作为包被其他程序调用 具体步骤: 选中项目文件,点右键选择 Export ,JAR File 在弹出窗口选择,导出哪些文件,并且选择好 输出 JAR 的路 ...
- Uva 派 (Pie,NWERC 2006,LA 3635)
依然是一道二分查找 #include<iostream> #include<cstdio> #include<cmath> using namespace std; ...
- PAT 乙级 1078 / 1084
题目 PAT 乙级 1078 PAT 乙级 1084 题解 1078和1084这两道题放在一块写,主要是因为这两道题的解法和做题思路非常相似:之前我做这一类题没有一个固定的套路,想到哪写到哪,在某种程 ...