Skip to content

Commit

Permalink
fix(ref): should not trigger when setting value to same proxy (#3658)
Browse files Browse the repository at this point in the history
  • Loading branch information
yangmingshan authored Jul 15, 2021
1 parent f6a5f09 commit 08f504c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
20 changes: 20 additions & 0 deletions packages/reactivity/__tests__/ref.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,4 +336,24 @@ describe('reactivity/ref', () => {
_trigger!()
expect(dummy).toBe(2)
})

test('should not trigger when setting value to same proxy', () => {
const obj = reactive({ count: 0 })

const a = ref(obj)
const spy1 = jest.fn(() => a.value)

effect(spy1)

a.value = obj
expect(spy1).toBeCalledTimes(1)

const b = shallowRef(obj)
const spy2 = jest.fn(() => b.value)

effect(spy2)

b.value = obj
expect(spy2).toBeCalledTimes(1)
})
})
10 changes: 7 additions & 3 deletions packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,15 @@ export function shallowRef(value?: unknown) {
}

class RefImpl<T> {
private _rawValue: T

private _value: T

public readonly __v_isRef = true

constructor(private _rawValue: T, public readonly _shallow: boolean) {
this._value = _shallow ? _rawValue : convert(_rawValue)
constructor(value: T, public readonly _shallow = false) {
this._rawValue = _shallow ? value : toRaw(value)
this._value = _shallow ? value : convert(value)
}

get value() {
Expand All @@ -66,7 +69,8 @@ class RefImpl<T> {
}

set value(newVal) {
if (hasChanged(toRaw(newVal), this._rawValue)) {
newVal = this._shallow ? newVal : toRaw(newVal)
if (hasChanged(newVal, this._rawValue)) {
this._rawValue = newVal
this._value = this._shallow ? newVal : convert(newVal)
trigger(toRaw(this), TriggerOpTypes.SET, 'value', newVal)
Expand Down

0 comments on commit 08f504c

Please sign in to comment.