性能检测
安装检测工具 npm i react-addons-perf --save
,然后在./app/index.jsx中写这段代码
import Perf from "react-addons-perf"
if(__DEV__){
window.Perf = Perf
}
如果报错:Perf is not defined
则删除上面代码第二行和第四行
运行程序,先在console里面打印Perf.start()
,然后在进行若干操作,在运行Perf.stop()
,然后再运行Perf.printWasted()
,即可打印出浪费性能的组件列表,在项目开发中,要经常使用检测工具来看性能是否正常。
PureRenderMixin性能优化
安装工具:npm i react-addons-pure-render-mixin --save
,然后在组件中引用
import React from "react"
import PureRednderMixin from "react-addons-pure-render-mixin"
export default class Index extends React.Component{
constructor(props,context){
super(props,context)
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this)
}
}
React有一个生命周期函数叫做shouleComponentUpdate,组件每次更新之前,都要过一遍这个函数,如果返回true
则更新,如果返回false
则不更新,而默认情况下,这个函数会一直返回true
,如果有一些无效的改动触发了这个函数,也会导致无效的更新!
什么是无效的改动?组件中props
和state
一旦发生改变就会导致组件重新更新并渲染,但是如果props和state没有变化也莫名其妙的出发更新呢(有这种情况),就会导致无效渲染。
这里使用
this.shouldComponentUpdate=PureRenderMixin.shouldComponentUpdate.bind(this)
的意思是重新组件的shouldComponentUpdate函数,在每次更新之前判断props和state,如果有变化返回ture
,没有则返回false
因此,在开发过程中,在每个React组件都尽量使用PureRenderMixin
filter( ) 过滤器
如果给定表示 DOM 元素集合的 jQuery 对象,.filter() 方法会用匹配元素的子集构造一个新的 jQuery 对象。所使用的选择器会测试每个元素;所有匹配该选择器的元素都会包含在结果中。
$('li').filter(':even').css('background-color', 'red');
//会选择偶数项使其背景色为红色 下标从0开始的
过滤函数
通过函数而不是选择器来筛选元素,对于每个元素,如果该函数返回true
,则元素会被包含在已筛选的集合中,否则会排除这个元素
<ul>
<li><strong>list</strong> item 1 - one strong tag</li>
<li><strong>list</strong> item <strong>2</strong>
- two <span>strong tags</span></li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
//js代码 选取这些列表项,然后基于其内容来筛选它们:
$('li').filter(function(index) {
return $('strong', this).length == 1;
}).css('background-color', 'red');
//tolist demo中的 可以不看这段代码
this.setState({
//遍历data 过滤数据
todos: data.filter(item => {
if (item.id !== id) {
return item
}
})
})