-
Notifications
You must be signed in to change notification settings - Fork 361
/
useReducer.tsx
49 lines (40 loc) ยท 1.12 KB
/
useReducer.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
type State = {
count: number;
};
type Action = { type: "up" | "down" | "reset"; payload?: State };
function init(count: State): State {
return count;
}
const initialState: State = { count: 0 };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "up":
return { count: state.count + 1 };
case "down":
return { count: state.count - 1 };
case "reset":
return init(action.payload || { count: 0 });
default:
throw new Error(`Unexpected action type ${action.type}`);
}
}
export default function App() {
const [state, dispatcher] = useReducer(reducer, initialState, init);
function handleUpButtonClick() {
dispatcher({ type: "up" });
}
function handleDownButtonClick() {
dispatcher({ type: "down" });
}
function handleResetButtonClick() {
dispatcher({ type: "reset", payload: { count: 1 } });
}
return (
<div>
<h1>{state.count}</h1>
<button onClick={handleDownButtonClick}>+</button>
<button onClick={handleDownButtonClick}>-</button>
<button onClick={handleResetButtonClick}>reset</button>
</div>
);
}