[inulax] 修复组件使用connect API,props里没有dispatch方法;修改对象比较算法,防止死循环

This commit is contained in:
huangxuan 2023-11-30 16:09:33 +08:00
parent 55af46db34
commit 3fb6652607
No known key found for this signature in database
GPG Key ID: E79F50C67022565D
2 changed files with 44 additions and 11 deletions

View File

@ -67,18 +67,50 @@ export function isPromise(obj: any): boolean {
return isObject(obj) && typeof obj.then === 'function'; return isObject(obj) && typeof obj.then === 'function';
} }
export function isSame(x, y) { export function isSame(x: unknown, y: unknown): boolean {
if (typeof Object.is !== 'function') { // 如果两个对象是同一个引用直接返回true
if (x === y) { if (x === y) {
// +0 != -0 return true;
return x !== 0 || 1 / x === 1 / y;
} else {
// NaN == NaN
return x !== x && y !== y;
}
} else {
return Object.is(x, y);
} }
// 如果两个对象类型不同直接返回false
if (typeof x !== typeof y) {
return false;
}
// 如果两个对象都是null或undefined直接返回true
if (x == null || y == null) {
return true;
}
// 如果两个对象都是基本类型,比较他们的值是否相等
if (typeof x !== 'object') {
return x === y;
}
// 如果两个对象都是数组,比较他们的长度是否相等,然后递归比较每个元素是否相等
if (Array.isArray(x) && Array.isArray(y)) {
if (x.length !== y.length) {
return false;
}
for (let i = 0; i < x.length; i++) {
if (!isSame(x[i], y[i])) {
return false;
}
}
return true;
}
// 两个对象都是普通对象,首先比较他们的属性数量是否相等,然后递归比较每个属性的值是否相等
if (typeof x === 'object' && typeof y === 'object') {
const keys1 = Object.keys(x!).sort();
const keys2 = Object.keys(y!).sort();
if (keys1.length !== keys2.length) {
return false;
}
for (let i = 0; i < keys1.length; i++) {
if (!isSame(x![keys1[i]], y![keys2[i]])) {
return false;
}
}
return true;
}
return false;
} }
export function getDetailedType(val: any) { export function getDetailedType(val: any) {

View File

@ -162,6 +162,7 @@ export function connect<StateProps, DispatchProps, OwnProps, MergedProps>(
mappedDispatch = mapDispatchToProps(store.dispatch, props); mappedDispatch = mapDispatchToProps(store.dispatch, props);
} }
} }
mappedDispatch = Object.assign({}, mappedDispatch, { dispatch: store.dispatch });
const mergedProps = ( const mergedProps = (
mergeProps || mergeProps ||
((state, dispatch, originalProps) => { ((state, dispatch, originalProps) => {