Skip to content

Commit

Permalink
Merge pull request alibaba#842 from linbudu599/fix/useReactive
Browse files Browse the repository at this point in the history
Fix/use reactive
  • Loading branch information
awmleer authored Jan 27, 2021
2 parents 684038c + 077735a commit 2925fc3
Show file tree
Hide file tree
Showing 2 changed files with 429 additions and 40 deletions.
21 changes: 18 additions & 3 deletions packages/hooks/src/useReactive/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,33 @@ import { useRef, useState } from 'react';

import useCreation from '../useCreation';

// k:v 原对象:代理过的对象
const proxyMap = new WeakMap();
// k:v 代理过的对象:原对象
const rawMap = new WeakMap();

function observer<T extends object>(initialVal: T, cb: () => void) {
function isObject(val: object): boolean {
return typeof val === 'object' && val !== null;
}

function observer<T extends object>(initialVal: T, cb: () => void): T {
const existingProxy = proxyMap.get(initialVal);

// 添加缓存 防止重新构建proxy
if (existingProxy) {
return existingProxy;
}

// 防止代理已经代理过的对象
// https://github.com/alibaba/hooks/issues/839
if (rawMap.has(initialVal)) {
return initialVal;
}

const proxy = new Proxy<T>(initialVal, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver);
return (typeof res === 'object' && res !== null) ? observer(res, cb) : Reflect.get(target, key);
return isObject(res) ? observer(res, cb) : Reflect.get(target, key);
},
set(target, key, val) {
const ret = Reflect.set(target, key, val);
Expand All @@ -24,6 +38,8 @@ function observer<T extends object>(initialVal: T, cb: () => void) {
});

proxyMap.set(initialVal, proxy);
rawMap.set(proxy, initialVal);

return proxy;
}

Expand All @@ -39,5 +55,4 @@ function useReactive<S extends object>(initialState: S): S {

return state;
}

export default useReactive;
Loading

0 comments on commit 2925fc3

Please sign in to comment.