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(reactivity): handle Set with initial reactive values edge case #12393

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
22 changes: 22 additions & 0 deletions packages/reactivity/__tests__/reactive.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,28 @@ describe('reactivity/reactive', () => {
expect(dummy).toBe(false)
})

// #8647
test('observing nest reactive in set', () => {
const observed = reactive({})
const observedSet = reactive(new Set([observed]))
expect(observedSet.size).toBe(1)
if (observedSet.has(observed)) {
// expect nothing happens
observedSet.add(observed)
}
expect(observedSet.size).toBe(1)

const observedMap = reactive(new Map())
observedMap.set('key', observed)
shengxj1 marked this conversation as resolved.
Show resolved Hide resolved
expect(observedMap.size).toBe(1)

if (observedMap.has(observed)) {
// expect nothing happens
observedMap.set('key1', observed)
}
expect(observedMap.size).toBe(1)
})

test('observed value should proxy mutations to original (Object)', () => {
const original: any = { foo: 1 }
const observed = reactive(original)
Expand Down
16 changes: 10 additions & 6 deletions packages/reactivity/src/collectionHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,15 +167,19 @@ function createInstrumentations(
}
: {
add(this: SetTypes, value: unknown) {
if (!shallow && !isShallow(value) && !isReadonly(value)) {
value = toRaw(value)
}
const target = toRaw(this)
const proto = getProto(target)
const hadKey = proto.has.call(target, value)
// 先获取原始值
shengxj1 marked this conversation as resolved.
Show resolved Hide resolved
const rawValue =
shengxj1 marked this conversation as resolved.
Show resolved Hide resolved
!shallow && !isShallow(value) && !isReadonly(value)
? toRaw(value)
: value
const hadKey =
proto.has.call(target, rawValue) ||
(value !== rawValue && proto.has.call(target, value))
if (!hadKey) {
target.add(value)
trigger(target, TriggerOpTypes.ADD, value, value)
target.add(rawValue)
trigger(target, TriggerOpTypes.ADD, rawValue, rawValue)
}
return this
},
Expand Down