Skip to content

Commit ffc39c8

Browse files
committed
添加initialAction参数支持;更新测试用例
1 parent 1ba90b1 commit ffc39c8

File tree

3 files changed

+21
-15
lines changed

3 files changed

+21
-15
lines changed

README.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,16 @@ npm i @saber2pr/use-reducer
77
# API
88

99
```ts
10-
const state = {
11-
div1: 100,
12-
div2: 1
10+
export const initState = {
11+
current: 100,
12+
delta: 1
1313
}
1414

1515
export const [getState, useReducer] = createStore(state)
1616

1717
// useReducer
18-
const [state, dispatch] = useReducer(reducer, initState)
18+
const [state, dispatch] = useReducer(reducer, initialState)
19+
// const [state, dispatch] = useReducer(reducer, initialState, initialAction)
1920

2021
// getState
2122
const globalState = getState()

src/core/createStore.ts

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ export type dispatch<A> = (action: A) => void
1212

1313
export type useReducer<S> = <A>(
1414
reducer: Reducer<S, A>,
15-
initialState: S
15+
initialState: S,
16+
initialAction?: A
1617
) => [S, dispatch<A>]
1718

1819
/**
@@ -29,15 +30,19 @@ export function createStore<S>(
2930
const __STORE: S = initialState
3031
const getState: getState<S> = () => __STORE
3132

32-
const useReducer: useReducer<S[keyof S]> = (reducer, initialState) => {
33-
const [state, setState] = React.useState(initialState)
34-
return [
35-
state,
36-
action =>
37-
setState(
38-
(__STORE[reducer.name] = reducer(state || initialState, action))
39-
)
40-
]
33+
const useReducer: useReducer<S[keyof S]> = (
34+
reducer,
35+
initialState,
36+
initialAction?
37+
) => {
38+
const initState = initialAction
39+
? reducer(initialState, initialAction)
40+
: initialState
41+
42+
const [state, setState] = React.useState(initState)
43+
__STORE[reducer.name] = state
44+
45+
return [state, action => setState(reducer(state, action))]
4146
}
4247

4348
return [getState, useReducer]

src/test/Delta.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { useReducer } from './store/store'
33
import { delta } from './store/delta'
44

55
export const Delta = ({ init }: { init: number }) => {
6-
const [state, dispatch] = useReducer(delta, init)
6+
const [state, dispatch] = useReducer(delta, init, { type: 'change' })
77
return (
88
<div>
99
delta:{state}

0 commit comments

Comments
 (0)