Skip to content

Commit

Permalink
fix(core): fix array field remove with memory leak (#2963)
Browse files Browse the repository at this point in the history
  • Loading branch information
janryWang authored Mar 20, 2022
1 parent 221d39f commit 1658ae3
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
49 changes: 49 additions & 0 deletions packages/core/src/__tests__/array.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createForm } from '../'
import { onFieldValueChange, onFormValuesChange } from '../effects'
import { DataField } from '../types'
import { attach } from './shared'

test('create array field', () => {
Expand Down Expand Up @@ -648,3 +649,51 @@ test('array field reset', () => {
expect(form.values).toEqual({ array: [] })
expect(array.value).toEqual([])
})

test('array field remove can not memory leak', async () => {
const handler = jest.fn()
const form = attach(
createForm({
values: {
array: [{ aa: 1 }, { aa: 2 }],
},
effects() {
onFieldValueChange('array.*.aa', handler)
},
})
)
const array = attach(
form.createArrayField({
name: 'array',
})
)
attach(
form.createObjectField({
name: '0',
basePath: 'array',
})
)
attach(
form.createField({
name: 'aa',
basePath: 'array.0',
})
)
attach(
form.createObjectField({
name: '1',
basePath: 'array',
})
)
attach(
form.createField({
name: 'aa',
basePath: 'array.1',
})
)
await array.remove(0)
form.query('array.0.aa').take((field) => {
;(field as DataField).value = '123'
})
expect(handler).toBeCalledTimes(2)
})
11 changes: 7 additions & 4 deletions packages/core/src/shared/internals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,10 @@ export const patchFieldStates = (
} else if (type === 'update') {
if (payload) {
target[address] = payload
if (target[oldAddress] === payload) delete target[oldAddress]
if (target[oldAddress] === payload) {
target[oldAddress]?.dispose()
delete target[oldAddress]
}
}
if (address && payload) {
locateNode(payload, address)
Expand Down Expand Up @@ -506,9 +509,9 @@ export const cleanupArrayChildren = (field: ArrayField, start: number) => {

const isNeedCleanup = (identifier: string) => {
const afterStr = identifier.slice(address.length)
const number = afterStr.match(NumberIndexReg)?.[1]
if (number === undefined) return false
const index = Number(number)
const numStr = afterStr.match(NumberIndexReg)?.[1]
if (numStr === undefined) return false
const index = Number(numStr)
return index >= start
}

Expand Down

0 comments on commit 1658ae3

Please sign in to comment.