diff --git a/src/reactivity/__tests__/effect.spec.ts b/src/reactivity/__tests__/effect.spec.ts index 6010da9..49c34d9 100644 --- a/src/reactivity/__tests__/effect.spec.ts +++ b/src/reactivity/__tests__/effect.spec.ts @@ -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) + + }) }); diff --git a/src/reactivity/src/effect.ts b/src/reactivity/src/effect.ts index e5f35f3..019e445 100644 --- a/src/reactivity/src/effect.ts +++ b/src/reactivity/src/effect.ts @@ -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 { @@ -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; }