Skip to content

Commit

Permalink
wip(okam-core): optimize redux state change check #11
Browse files Browse the repository at this point in the history
  • Loading branch information
wuhy committed Dec 3, 2018
1 parent f0aca25 commit d9d7cae
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ export default class ComputedObserver {
// so if the old === value && typeof old === 'object', it'll also need
// to update view
if (old !== value || (typeof old === 'object')) {
let needUpdate = this.shouldUpdate ? this.shouldUpdate(old, value) : true;
if (!needUpdate) {
return;
}

ctx.data[p] = value;
ctx.$setData({[p]: value});
this.notifyWatcher(value, old, [p]);
Expand Down
8 changes: 8 additions & 0 deletions packages/okam-core/src/extend/data/redux/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

'use strict';

import isValueEqual from './equal';

/* eslint-disable fecs-prefer-destructure */

function normalizeStoreComputed(stateMap) {
Expand Down Expand Up @@ -84,13 +86,19 @@ function normalizeStoreActions(actionMap) {
return toAction;
}

function shouldUpdate(old, curr) {
return !isValueEqual(old, curr);
}

function onStoreChange() {
let observer = this.__computedObserver;
let upKeys = this.__storeComputedKeys;
if (typeof upKeys === 'function') {
this.__storeComputedKeys = upKeys = upKeys();
}

if (observer && upKeys) {
observer.shouldUpdate || (observer.shouldUpdate = shouldUpdate);
upKeys.forEach(k => observer.updateComputed(k));
}
}
Expand Down
57 changes: 57 additions & 0 deletions packages/okam-core/src/extend/data/redux/equal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* @file Check the changed value is equal
* @author [email protected]
*/

'use strict';

import {isPlainObject} from '../../../util/index';

function isShadowEqual(obj1, obj2) {
let keys = Object.keys(obj1);
let keys2 = Object.keys(obj2);

if (keys.length !== keys2.length) {
return false;
}

return !keys.some(k => {
if (obj1[k] !== obj2[k]) {
return true;
}
return false;
});
}

function isArrayValueEqual(arr1, arr2) {
let len = arr1.length;
if (len !== arr2.length) {
return false;
}

for (let i = 0; i < len; i++) {
let item1 = arr1[i];
let item2 = arr2[i];
if (item1 !== item2) {
return false;
}
}

return true;
}

export default function isValueEqual(old, curr) {
if (old === curr) {
return true;
}

if (isPlainObject(old) && isPlainObject(curr)) {
return isShadowEqual(old, curr);
}

if (Array.isArray(old) && Array.isArray(curr)) {
return isArrayValueEqual(old, curr);
}

return false;
}

0 comments on commit d9d7cae

Please sign in to comment.