react与mox-react的shouldComponentUpdate 理解

时间:2023-03-09 03:17:32
react与mox-react的shouldComponentUpdate 理解

react性能优化中,提到的就是通过 React.PureComponent 替换 React.Component 组件进行编程。

两个组件之间的不同主要就是PureComponent做了shouldComponentUpdate的优化。对props和state进行了第一层的值===比较, 并且对 context 的变化不进行判断。

通过查看React可以看到

react与mox-react的shouldComponentUpdate 理解

react与mox-react的shouldComponentUpdate 理解

 /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*
*/ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
// Added the nonzero y check to make Flow happy, but it is redundant
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
} /**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (is(objA, objB)) {
return true;
} if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
} var keysA = Object.keys(objA);
var keysB = Object.keys(objB); if (keysA.length !== keysB.length) {
return false;
} // Test for A's keys different from B.
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
} return true;
} module.exports = shallowEqual;

shallowEqual

项目准备升级 React16,控制台出现了错误 shouldComponentUpdate should not be used when extending React.PureComponent.

一开始看很莫名其妙,明明组件没有自己写shouldComponentUpdate,怎么就报错了。

后来谷歌了下,原来是项目使用了mobx进行的状态管理。使用mox-react,对所有组件都通过 @observer 装饰器,以前也看过mobx-react源码,里面的确mixin了shouldComponentUpdate方法,优化了组件的性能

看下面的源代码

 function mixinLifecycleEvents(target) {
patch(target, "componentWillMount", true)
;["componentDidMount", "componentWillUnmount", "componentDidUpdate"].forEach(function (
funcName
) {
patch(target, funcName)
})
if (!target.shouldComponentUpdate) {
target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate
}
}
{
shouldComponentUpdate: function(nextProps, nextState) {
if (isUsingStaticRendering) {
console.warn(
"[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side."
)
}
// update on any state changes (as is the default)
if (this.state !== nextState) {
return true
}
// update if props are shallowly not equal, inspired by PureRenderMixin
// we could return just 'false' here, and avoid the `skipRender` checks etc
// however, it is nicer if lifecycle events are triggered like usually,
// so we return true here if props are shallowly modified.
return isObjectShallowModified(this.props, nextProps)
}
}
function isObjectShallowModified(prev, next) {
if (null == prev || null == next || typeof prev !== "object" || typeof next !== "object") {
return prev !== next
}
const keys = Object.keys(prev)
if (keys.length !== Object.keys(next).length) {
return true
}
let key
for (let i = keys.length - 1; i >= 0, (key = keys[i]); i--) {
if (next[key] !== prev[key]) {
return true
}
}
return false
}

经过测试,使用setState后,shouldComponentUpdate 的确 this.state!==nextState,但是对于this.props, nextProps的判断,还是存在一些差别的。

可以试下下面的比较

console.log(isObjectShallowModified(NaN, NaN), !shallowEqual(NaN, NaN));

var a = {a: 1}, b = {b: 1, __proto__: {a: 1}};
console.log(isObjectShallowModified(a, b), !shallowEqual(a, b));

对于一些比较简单的对象比较结果还是相同的,所以对于@observer的组件就改为了React.Component进行处理。