很多人在写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组件-传值篇的更多相关文章

  1. React组件传值方式总结

    1. 子组件向父组件传值 父组件Header: import Nav from 'Nav.js'; class Header extends React.Component { constructor ...

  2. 深入理解React组件传值(组合和继承)

    在文章之前,先把这句话读三遍 Props 和组合为你提供了清晰而安全地定制组件外观和行为的灵活方式.注意:组件可以接受任意 props,包括基本数据类型,React 元素以及函数. 来源于React中 ...

  3. React 组件传值 父传递儿子

    10===> 传递参数 import React from "react" //一定要导入React // 函数类型去创建组件 export function Web1(pr ...

  4. React组件传值

    React的单向数据流与组件间的沟通. 首先,我认为使用React的最大好处在于:功能组件化,遵守前端可维护的原则. 先介绍单向数据流吧. React单向数据流: React是单向数据流,数据主要从父 ...

  5. 我们编写 React 组件的最佳实践

    刚接触 React 的时候,在一个又一个的教程上面看到很多种编写组件的方法,尽管那时候 React 框架已经相当成熟,但是并没有一个固定的规则去规范我们去写代码. 在过去的一年里,我们在不断的完善我们 ...

  6. 编写React组件的最佳实践

    此文翻译自这里. 当我刚开始写React的时候,我看过很多写组件的方法.一百篇教程就有一百种写法.虽然React本身已经成熟了,但是如何使用它似乎还没有一个"正确"的方法.所以我( ...

  7. React子组件与父组件传值

    一 子组件向父组件传值 //子组件var Child = React.createClass({ render: function(){ return ( <div> 请输入邮箱:< ...

  8. React学习笔记(三) 组件传值

    组件嵌套后,父组件怎么向子组件发送数据呢? 答案是: this.props <script type="text/babel"> var MyFirst = React ...

  9. 使用React.cloneElement()给子组件传值

    React提供了一个克隆组件的API: React.cloneElement( element, [props], [...child] ) 可以利用该方法,给子组件传值,使用如下: class Pa ...

随机推荐

  1. SQL Server 08版与14版处理重复行的方式

    在项目中,利用循环拼接成了插入多行数据的SQL语句: Insert into table(col1,col2)vaules(value11,value21); Insert into table(co ...

  2. web调试的一些小技巧

    1.不带缓存的刷新,用于刷新css或者js:Ctrl+F5 待续...

  3. ZooKeeper保证之单一视图(Single System Image)

    由于ZooKeeper的数据模型简单且全部在内存中,ZooKeeper的速度非常快.它提供了一系列保证(Guarantees): • 顺序一致性(Sequential Consistency) • 原 ...

  4. signal函数:void (*signal(int,void(*)(int)))(int);

    http://blog.chinaunix.net/uid-20178794-id-1972862.html signal函数:void (*signal(int,void(*)(int)))(int ...

  5. 【BZOJ1857】传送带(分治经典:三分套三分)

    点此看题面 大致题意: 一个二维平面上有两条传送带\(AB\)和\(CD\),\(AB\)传送带的移动速度为\(P\),\(CD\)传送带的移动速度为\(Q\),步行速度为\(R\),问你从\(A\) ...

  6. 2018.10.05 TOPOI提高组模拟赛 解题报告

    得分: \(100+5+100=205\)(真的是出乎意料) \(T1\):抵制克苏恩(点此看题面) 原题: [BZOJ4832][Lydsy1704月赛] 抵制克苏恩 应该还是一个比较简单的\(DP ...

  7. 【BZOJ1972】[SDOI2010] 猪国杀(恶心的大模拟)

    点此看题面 大致题意: 让你模拟一个游戏猪国杀的过程. 几大坑点 对于这种模拟题,具体思路就不讲了,就说说有哪些坑点. 题面有锅,反猪是\(FP\). 数据有锅,牌堆中的牌可能不够用,牌堆为空之后需一 ...

  8. 2018.5.17 oracle函数查询

    --*********函数*********** --1.显示当前日期 select sysdate from dual; --2.显示当前日期,格式为****年月日,别名为hday select t ...

  9. Mac 系统 + Chrome浏览器 网页前端出现中文文字反转或顺序错乱

    问题背景 React开发的系统,收到一个BUG反馈,*"号个人统计"文字不正确,应为"个人号统计"*. 收到BUG后,打开浏览器查验是什么情况,难道犯了最基本的 ...

  10. 【原创】数据处理中判断空值的方法(np.isnan、is np.nan和pd.isna)比较

      转载请注明出处:https://www.cnblogs.com/oceanicstar/p/10869725.html  1.np.isnan(只有数组数值运算时可使用) 注意:numpy模块的i ...