Skip to content

Commit

Permalink
fix(reactive): fix computed value can not get real value (#2389)
Browse files Browse the repository at this point in the history
  • Loading branch information
janryWang authored Nov 3, 2021
1 parent 0adf07a commit eb34b2d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/core/src/models/Field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,13 +233,14 @@ export class Field<
reaction(
() => this.display,
(display) => {
const value = this.value
if (display === 'visible') {
if (isEmpty(this.value)) {
if (isEmpty(value)) {
this.setValue(this.caches.value)
this.caches.value = undefined
}
} else {
this.caches.value = toJS(this.value)
this.caches.value = toJS(value)
if (display === 'none') {
this.form.deleteValuesIn(this.path)
}
Expand Down
21 changes: 21 additions & 0 deletions packages/reactive/src/__tests__/autorun.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,3 +542,24 @@ test('autorun dispose in batch', () => {
})
expect(handler).toBeCalledTimes(1)
})

test('atom mutate value by computed depend', () => {
const obs = observable<any>({})
const comp1 = observable.computed(() => {
return obs.aa?.bb
})
const comp2 = observable.computed(() => {
return obs.aa?.cc
})
const handler = jest.fn()
autorun(() => {
handler(comp1.value, comp2.value)
})
obs.aa = {
bb: 123,
cc: 321,
}
expect(handler).toBeCalledTimes(2)
expect(handler).toBeCalledWith(undefined, undefined)
expect(handler).toBeCalledWith(123, 321)
})
4 changes: 4 additions & 0 deletions packages/reactive/src/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {
batchEnd,
batchStart,
bindTargetKeyWithCurrentReaction,
runReactionsFromTargetKey,
} from './reaction'
Expand Down Expand Up @@ -200,6 +202,7 @@ export const baseHandlers: ProxyHandler<any> = {
const newValue = createObservable(target, key, value)
const oldValue = target[key]
target[key] = newValue // use Reflect.set is too slow
batchStart()
if (!hadKey) {
runReactionsFromTargetKey({
target,
Expand All @@ -219,6 +222,7 @@ export const baseHandlers: ProxyHandler<any> = {
type: 'set',
})
}
batchEnd()
return true
},
deleteProperty(target, key) {
Expand Down

0 comments on commit eb34b2d

Please sign in to comment.