react 小记
来源:互联网 发布:aop切面编程 性能 编辑:程序博客网 时间:2024/06/16 05:51
本文主要记录在react项目中遇到的一些小问题
组件更新
当在组件前套的情况下,在组件挂载之后的更新阶段,当父组件的shouldComponentUpdate
返回值为true的时候,子组件会重新实例化生成一个新的,重新走一遍constructor
函数,在这个阶段子组件内部的 shoudldComponentUpdate
不会执行。子组件内部的生命周期方法负责本身的状态管理和更新
组件传递
在做Draft.js编辑器的扩展机制的时候,需要渲染用户自定义组件,这时候组件组件是作为参数传递进来的,然后编辑器负责渲染,实现如下:
//传递组件: this.extendDecorator = [ { strategy: BugTest.strategy,//策略 component: BugTest, //定义好组件后,传递过去 } ]//组件渲染render(){ let Com=this.extendDecorator[0].component; return <Com data="test">}
需要传参的箭头函数绑定
尽量避免在render内部使用箭头函数:
//不推荐的写法:render(){ return (<div onClick={(data)=>this.handleSave(data)}></div>)}//建议将handleSave改为如下,避免在render内部使用箭头函数:hanldeSave=(data)=>()=>{ //do something here}render(){ return <div onClick={this.handleSave(data)}></div>}
shouldComponentUpdate与Immutable结合提升性能
shouldComponentUpdate
默认下返回true,即:总是执行render,在应用遇到性能瓶颈的时候,可以借助此方法,减少重复渲染,提升性能。
对于引用类型的数据进行比较的时候,简单实用’===’是不够的,我们需要知道其数据是否发生过改变,当然,我们可以使用 deepCopy 和 deepCompare 来避免无必要的 render(),但 deepCopy 和 deepCompare 一般都是非常耗性能的。这时候有如下的方法:
使用JSON.strinfify(),然后比较
特点:简单粗暴,只适用于纯值的对象或者数组(不能包含function或者dom节点),而且当仅仅是数据的顺序发生改变的时候,也返回false
结合Immutable.is
import { is } from 'immutable';shouldComponentUpdate: (nextProps = {}, nextState = {}) => { const thisProps = this.props || {}, thisState = this.state || {}; 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 (thisState[key] !== nextState[key] || !is(thisState[key], nextState[key])) { return true; } } return false;}
特点:成本低,性能好(有待考究)
本段的参考链接
0 0
- react 小记
- react 小记
- 小记react-native 安装
- React-native小记
- react使用小记1
- react-native小记
- React学习小记
- React-Redux学习小记
- Android React Native植入原生应用小记
- React native 环境安装配置小记
- React Native react-native-vector-icons 使用小记
- 小记
- 小记
- 小记
- 小记
- 小记
- 小记
- 小记
- 小问题解决汇总
- IE8下css中滤镜filter的颜色渐变
- C#之玩转反射
- linux shell--变量赋值
- Spring JDBC 常用批量操作及插入操作
- react 小记
- 纯CSS3实现多啦a梦—感觉萌萌哒
- 浅谈Servlet的Web服务器
- jQuery UI Autocomplete ajax动态赋值实例
- Java对象的序列化和反序列化
- 曾经映射到AIX主机的存储LUN在存储断开(光纤线拔掉)的情况下的ls -rlt /dev/和lspv的结果差异
- HDU 2516 取石子游戏 斐波那契博弈裸题
- 获取iPhone手机的型号 iOS
- Android 文件及文件夹删除