Skip to content

Commit

Permalink
feat(useStaged): 支持 reset 重置暂存状态
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 4, 2021
1 parent 97d93e7 commit 8edd7e1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
19 changes: 13 additions & 6 deletions src/react/useStaged.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,42 @@ describe('useStaged', () => {
test('表现正常', () => {
const { result } = renderHook(() => {
const [counter, setCounter] = useState(1)
const [stagedCounter, setStagedCounter, commitStagedCounter] = useStaged(
const [stagedCounter, stagedCounterActions] = useStaged(
counter,
setCounter,
)
return {
counter,
setCounter,
stagedCounter,
setStagedCounter,
commitStagedCounter,
stagedCounterActions,
}
})
expect(result.current.counter).toBe(1)
expect(result.current.stagedCounter).toBe(1)

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

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

act(() => result.current.commitStagedCounter())
act(() => result.current.stagedCounterActions.commit())
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)

act(() => result.current.stagedCounterActions.set(300))
expect(result.current.counter).toBe(0)
expect(result.current.stagedCounter).toBe(300)

act(() => result.current.stagedCounterActions.reset())
expect(result.current.counter).toBe(0)
expect(result.current.stagedCounter).toBe(0)
})
})
26 changes: 22 additions & 4 deletions src/react/useStaged.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,33 @@ import { useStateWithDeps } from './useStateWithDeps'
/**
* 暂存状态。
*/
export function useStaged<T extends any, F extends (value: T) => void>(
export function useStaged<T>(
value: T,
setValue: F,
): [T, F, () => void] {
setValue: (value: T) => void,
): [
T,
{
set: (value: T) => void
commit: () => void
reset: () => void
},
] {
const [stagedState, setStagedState] = useStateWithDeps(value, [value])
const valueRef = useLatest(value)
const setValueRef = useLatest(setValue)
const stagedStateRef = useLatest(stagedState)
const commitStagedState = useCallback(() => {
setValueRef.current(stagedStateRef.current)
}, [])
return [stagedState, setStagedState, commitStagedState] as any
const resetStagedState = useCallback(() => {
setStagedState(valueRef.current)
}, [])
return [
stagedState,
{
set: setStagedState,
commit: commitStagedState,
reset: resetStagedState,
},
]
}

0 comments on commit 8edd7e1

Please sign in to comment.