react 学习总结8–性能提升
性能提升总结
基本上就是参照了这篇文章,可以直接去看
写这篇文章主要是为了做一个记录,公司项目暂时不会使用 immutable 等。
- 谨慎使用 setState,容易导致重新渲染
- 方法的 bind ,写在 constructor 中
- 传递给组件的 props,一定要是有用的,减少 shouldComponentUpdate 的负担,减少使用{…props}
- 使用 pure-render-decorator 减少 没有必要的 render
- 使用 immutable 定义 props state store
pure-render-decorator 使用示例
安装
sudo npm install --save pure-render-decorator
引入
import pureRender from 'pure-render-decorator';
使用
export default pureRender(Component);
,pureRender 会动态的给 Component 重写一个 shouldComponentUpdate 来判断是否需要re-render缺陷 pureRender 只是在浅层次的对比,引用类型的数据只会比较引用地址,所以,如果引用地址改变,但是内容不变还是会re-render
immutable 在react 中的使用
学习参照了这篇文章,可以代替原本的
Object.assign({}, state, {})
这样的浅层次拷贝
1.创建 reducer
安装
sudo npm install --save redux-immutable
,然后在项目中引用
import {combineReducers} from 'redux-immutable';
代替原本redux 的combineReducers
,其他使用照常改变
routReducer
, 重新写一个routing.js
,如下,并将其合并到主reducer上
import Immutable from 'immutable';
import { LOCATION_CHANGE } from 'react-router-redux';
const initialState = Immutable.fromJS({
locationBeforeTransitions: null
});
export default (state = initialState, action) => {
if (action.type === LOCATION_CHANGE) {
return state.set('locationBeforeTransitions', action.payload);
}
return state;
};
2.创建store
创建store 需要多加一个参数,以配合routing,如下
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState (state) {
return state.get('routing').toObject();
}
});
3.创建action
注意返回值不能直接是Map类型,action 需要返回一个包含type属性的对象
import {fromJS} from 'immutable';
export function login () {
return {
type : LOGIN,
msg : fromJS({
isLogin: true,
balance: 1000,
list : [
{name : 'Child1',age:20},
{name : 'Child1',age:10},
{name : 'Child1',age:0},
{name : 'Child1',age:0}
]
})
};
}
4. 创建comtainer
export default connect(
state => ({testState : state.toObject().testReducer}),
dispatch => ({
login : bindActionCreators(login, dispatch),
logout : bindActionCreators(logout, dispatch)
})
)(Test);
5. 一般使用的方法
- .set(key,value) 设置值
- .get(key) 获取值
- .merge({}) 合并值
- .mergeDeep({}) 深度合并值
- toJS() 转化为js(深度)
- fromJS() 转化为不可变数据 (深度)
- toObject() 浅度转化为对象