Skip to content

Commit

Permalink
feat(react): 新增 useStaged 暂存状态
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 4, 2021
1 parent b753073 commit 7fd1181
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/react/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ export * from './useEnvironment'
export * from './useLoadMore'
export * from './useReachBottom'
export * from './useScrollLoadMore'
export * from './useStaged'
export * from './useStateWithDeps'
export * from './useValidator'
// @endindex
Expand Down
40 changes: 40 additions & 0 deletions src/react/useStaged.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { act, renderHook } from '@testing-library/react-hooks'
import { useStaged } from './useStaged'
import { useState } from 'react'

describe('useStaged', () => {
test('表现正常', () => {
const { result } = renderHook(() => {
const [counter, setCounter] = useState(1)
const [stagedCounter, setStagedCounter, commitStagedCounter] = useStaged(
counter,
setCounter,
)
return {
counter,
setCounter,
stagedCounter,
setStagedCounter,
commitStagedCounter,
}
})
expect(result.current.counter).toBe(1)
expect(result.current.stagedCounter).toBe(1)

act(() => result.current.setStagedCounter(2))
expect(result.current.counter).toBe(1)
expect(result.current.stagedCounter).toBe(2)

act(() => result.current.setStagedCounter(3))
expect(result.current.counter).toBe(1)
expect(result.current.stagedCounter).toBe(3)

act(() => result.current.commitStagedCounter())
expect(result.current.counter).toBe(3)
expect(result.current.stagedCounter).toBe(3)

act(() => result.current.setCounter(0))
expect(result.current.counter).toBe(0)
expect(result.current.stagedCounter).toBe(0)
})
})
19 changes: 19 additions & 0 deletions src/react/useStaged.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useCallback } from 'react'
import { useLatest } from 'react-use'
import { useStateWithDeps } from './useStateWithDeps'

/**
* 暂存状态。
*/
export function useStaged<T extends any, F extends (value: T) => void>(
value: T,
setValue: F,
): [T, F, () => void] {
const [stagedState, setStagedState] = useStateWithDeps(value, [value])
const setValueRef = useLatest(setValue)
const stagedStateRef = useLatest(stagedState)
const commitStagedState = useCallback(() => {
setValueRef.current(stagedStateRef.current)
}, [])
return [stagedState, setStagedState, commitStagedState] as any
}

0 comments on commit 7fd1181

Please sign in to comment.