Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复effect不可嵌套问题 #65

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/reactivity/__tests__/effect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,33 @@ describe("effect", () => {
stop(runner);
expect(onStop).toHaveBeenCalled();
});

it('nested effect', () => {
const obj = reactive({ foo: 1, bar: 1 })
let temp1, temp2
const outerCall = jest.fn()
const innerCall = jest.fn()
effect(() => {
outerCall()
effect(() => {
innerCall()
temp2 = obj.bar
})
temp1 = obj.foo
})
// 两个都会执行
expect(outerCall).toBeCalledTimes(1)
expect(innerCall).toBeCalledTimes(1)

obj.bar = 2
// 只执行内层的
expect(outerCall).toBeCalledTimes(1)
expect(innerCall).toBeCalledTimes(2)

obj.foo = 2
// 内外层都执行
expect(outerCall).toBeCalledTimes(2)
expect(innerCall).toBeCalledTimes(3)

})
});
9 changes: 7 additions & 2 deletions src/reactivity/src/effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { extend } from "../../shared/index";
let activeEffect = void 0;
let shouldTrack = false;
const targetMap = new WeakMap();
const effectStack: any[] = []

// 用于依赖收集
export class ReactiveEffect {
Expand Down Expand Up @@ -34,12 +35,16 @@ export class ReactiveEffect {
// 执行的时候给全局的 activeEffect 赋值
// 利用全局属性来获取当前的 effect
activeEffect = this as any;
effectStack.push(this)
// 执行用户传入的 fn
console.log("执行用户传入的 fn");
const result = this.fn();
effectStack.pop()
activeEffect = effectStack[effectStack.length - 1]
// 重置
shouldTrack = false;
activeEffect = undefined;
if (effectStack.length === 0) {
shouldTrack = false
}

return result;
}
Expand Down