Created
November 10, 2024 19:23
-
-
Save yukikim/a5c1c234ba2121f9407a9e695b0508b6 to your computer and use it in GitHub Desktop.
[tsx]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'; | |
// それぞれのコンポーネント | |
const ComponentA: React.FC = () => <div>Component A</div>; | |
const ComponentB: React.FC = () => <div>Component B</div>; | |
const ComponentC: React.FC = () => <div>Component C</div>; | |
// reducer のアクション型 | |
type Action = { type: 'showA' } | { type: 'showB' } | { type: 'showC' }; | |
// reducer の実装 | |
const reducer = (state: string, action: Action): string => { | |
switch (action.type) { | |
case 'showA': | |
return 'A'; | |
case 'showB': | |
return 'B'; | |
case 'showC': | |
return 'C'; | |
default: | |
return state; | |
} | |
}; | |
const MyComponent: React.FC = () => { | |
// useReducer を使ってステートと dispatch を定義 | |
const [currentComponent, dispatch] = useReducer(reducer, 'A'); | |
// ステートに応じたコンポーネントを切り替え | |
let renderedComponent; | |
switch (currentComponent) { | |
case 'A': | |
renderedComponent = <ComponentA />; | |
break; | |
case 'B': | |
renderedComponent = <ComponentB />; | |
break; | |
case 'C': | |
renderedComponent = <ComponentC />; | |
break; | |
default: | |
renderedComponent = <div>Invalid Component</div>; | |
break; | |
} | |
return ( | |
<div> | |
<div> | |
<button onClick={() => dispatch({ type: 'showA' })}>Show A</button> | |
<button onClick={() => dispatch({ type: 'showB' })}>Show B</button> | |
<button onClick={() => dispatch({ type: 'showC' })}>Show C</button> | |
</div> | |
{renderedComponent} | |
</div> | |
); | |
}; | |
export default MyComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment