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

fix: nested effect #114

Open
wants to merge 1 commit 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
33 changes: 33 additions & 0 deletions packages/reactivity/__tests__/effect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,37 @@ describe("effect", () => {
stop(runner);
expect(onStop).toHaveBeenCalled();
});

it('should correctly track the order of nested effects', () => {
const counter = reactive({
outerCount: 0,
innerCount: 0,
})

let executionOrder: string[] = []

effect(() => {
effect(() => {
counter.innerCount
executionOrder.push('inner')
})
counter.outerCount
executionOrder.push('outer')
})

// init effect
expect(executionOrder).toEqual(['inner', 'outer'])

// reset
executionOrder = []

counter.outerCount++
expect(executionOrder).toEqual(['inner', 'outer'])

// reset
executionOrder = []

counter.innerCount++
expect(executionOrder).toEqual(['inner', 'inner'])
})
});
41 changes: 26 additions & 15 deletions packages/reactivity/src/effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,32 @@ export class ReactiveEffect {
return this.fn();
}

// 执行 fn 收集依赖
// 可以开始收集依赖了
shouldTrack = true;

// 执行的时候给全局的 activeEffect 赋值
// 利用全局属性来获取当前的 effect
activeEffect = this as any;
// 执行用户传入的 fn
console.log("执行用户传入的 fn");
const result = this.fn();
// 重置
shouldTrack = false;
activeEffect = undefined;

return result;
// 保存嵌套effect外层effect的 activeEffect 和 shouldTrack
let lastEffect = activeEffect;
let lastShouldTrack = shouldTrack;

try {
// 执行 fn 收集依赖
// 可以开始收集依赖了
shouldTrack = true;

// 执行的时候给全局的 activeEffect 赋值
// 利用全局属性来获取当前的 effect
activeEffect = this as any;
// 执行用户传入的 fn
console.log("执行用户传入的 fn");
const result = this.fn();
// 重置
shouldTrack = false;
activeEffect = undefined;

return result;
} finally {
// 内层 effect 执行完毕
// 取出外层 effect 的 activeEffect 和 shouldTrack
activeEffect = lastEffect;
shouldTrack = lastShouldTrack;
}
}

stop() {
Expand Down