Skip to content

Commit

Permalink
chore(reactive): improve strict mode update strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
janryWang committed Jun 27, 2022
1 parent 5c12281 commit c3002bd
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 13 deletions.
18 changes: 11 additions & 7 deletions packages/reactive-react/src/hooks/useForceUpdate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useRef, useState } from 'react'
import { useLayoutEffect } from './useLayoutEffect'
import { useDidUpdate } from './useDidUpdate'

const EMPTY_ARRAY: any[] = []
Expand All @@ -7,17 +8,20 @@ const RENDER_QUEUE = new Set<() => void>()

export function useForceUpdate() {
const [, setState] = useState([])
const unMountRef = useRef(false)

useEffect(() => {
unMountRef.current = false
const renderedRef = useRef(false)
useLayoutEffect(() => {
renderedRef.current = true
return () => {
unMountRef.current = true
renderedRef.current = false
}
}, EMPTY_ARRAY)

const update = useCallback(() => {
if (unMountRef.current) return
if (!renderedRef.current) {
// 针对StrictMode无法快速回收内存,只能考虑拦截第一次渲染函数的setState,
// 因为第一次渲染函数的setState会触发第二次渲染函数执行,从而清理掉第二次渲染函数内部的依赖
return
}
setState([])
}, EMPTY_ARRAY)

Expand Down
6 changes: 2 additions & 4 deletions packages/reactive-react/src/hooks/useObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ export const useObserver = <T extends () => any>(
)
if (!trackerRef.current) {
trackerRef.current = new Tracker(() => {
if (!mountedRef.current) return
if (typeof options?.scheduler === 'function') {
options.scheduler(forceUpdate)
} else {
Expand All @@ -43,19 +42,18 @@ export const useObserver = <T extends () => any>(
}

React.useEffect(() => {
mountedRef.current = true
gcRef.current.close()
const dispose = () => {
if (trackerRef.current && !mountedRef.current) {
trackerRef.current.dispose()
trackerRef.current = null
}
}
mountedRef.current = true
gcRef.current.close()
return () => {
mountedRef.current = false
immediate(dispose)
}
}, [])

return trackerRef.current.track(view)
}
3 changes: 1 addition & 2 deletions packages/reactive/src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@ export class ArraySet<T> {
}

delete(item: T) {
const eachIndex = this.forEachIndex
const findIndex = this.value.indexOf(item)
if (findIndex > -1) {
this.value.splice(findIndex, 1)
if (findIndex <= eachIndex) {
if (findIndex <= this.forEachIndex) {
this.forEachIndex -= 1
}
}
Expand Down

0 comments on commit c3002bd

Please sign in to comment.