Created
November 25, 2019 16:20
-
-
Save kuwabataK/22fb580f1ca81f7e5b2d84e4382e6644 to your computer and use it in GitHub Desktop.
useReducerの型定義例です
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer } from "react"; | |
import "./App.css"; | |
const initialState = { count: 0, str: "" }; | |
type ActionTypes = | |
{ | |
type: "increment"; | |
payload: { num: number }; | |
} | |
| { | |
type: "decrement"; | |
payload: { num: number }; | |
} | |
| { | |
type: "reset"; | |
} | |
| { | |
type: "setStr"; | |
payload: { str: string }; | |
}; | |
const reducer = (state: typeof initialState, action: ActionTypes) => { | |
switch (action.type) { | |
case "increment": | |
return { ...state, count: state.count + action.payload.num }; | |
case "decrement": | |
return { ...state, count: state.count - action.payload.num }; | |
case "reset": | |
return initialState; | |
case "setStr": | |
return { ...state, str: action.payload.str }; | |
default: | |
throw new Error(); | |
} | |
}; | |
const App = () => { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const inc = () => { | |
dispatch({ type: "increment", payload: { num: 1 } }); | |
}; | |
const dec = () => { | |
dispatch({ type: "decrement", payload: { num: 1 } }); | |
}; | |
const reset = () => { | |
dispatch({ type: "reset" }); | |
}; | |
const setStr = () => { | |
dispatch({type:'setStr', payload:{str: '新しい文字だよ'}}) | |
} | |
return ( | |
<div className="App"> | |
カウンター: {state.count} | |
文字列: {state.str} | |
<button onClick={inc}>カウントを増加させる</button> | |
<button onClick={dec}>カウントを減らす</button> | |
<button onClick={reset}>カウントをリセット</button> | |
<button onClick={setStr}>文字列を更新</button> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment