1,react的 虚拟dom
react在修改前后的虚拟dom树的比较运算,都是同级之间进行比较,这样的算法 就很高效,是O(1)常数的,
还有就是递归的算法,就比较的低效,是O(n2) ;
ReactElement.createElement = function (type, config, children) {
var propName;
// 初始化参数
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
// 从config中提取出内容,如ref key props
if (config != null) {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + config.key;
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// 提取出config中的prop,放入props变量中
for (propName in config) {
if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// 处理children,挂到props的children属性下
// 入参的前两个为type和config,后面的就都是children参数了。故需要减2
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
// 只有一个参数时,直接挂到children属性下,不是array的方式
props.children = children;
} else if (childrenLength > 1) {
// 不止一个时,放到array中,然后将array挂到children属性下
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// 取出组件类中的静态变量defaultProps,并给未在JSX中设置值的属性设置默认值
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
// 返回一个ReactElement对象
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
- 1
入参三个, 类型 ,配置, 有无包含内容。
最终返回一个ReactElement对象,
源码
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE, // ReactElement对象上的四个变量,特别关键
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner };
return element;
}
最后发现其实是个对象
虚拟dom里做比较其实就是两个ReactElement之间的比较;这样的比较是高效的; 这就是diff算法;
然后算法完成后会拿到结果,走一个switch去匹配是否增加还是删除还是修改的操作;
2。
组件生命周期的优化
生命周期分为两类 :组件的初始化和组件的更新。
更新也分为两种(父组件的props更新,和this.setState方法的调用,最终会走向shouldComponentUpdate这个方法);
这里优化的点主要在于组件的 更新的时候:
shouldComponentUpdate(nextProps,nextState ); 这里 如果 返回true 才会往下走,如果是false那么就会打住,
这样的话 那么这边我们就可以控制传入true的次数 ,以达到最小渲染次数来减少损耗;
入参的话是个nextProps,nextState;
这个关键的条件是 nextstate如果不同于 this.state ,那么去渲染才是高效的,而不是每次this.setState都要渲染,
setState 有个异步队列去实现更新,也就是说是异步来的,
由于setState会导致render,所以在render函数里不要setState,否则 又来一遍。很危险。
后面会补充shouldComponentUpdate如何配合组件去优化