Redux
Reduxは React以外にも使える(Vue.js, Angular, VanillaJS....etc)
差分は?
Providerが使える
connectが使える?
https://scrapbox.io/files/635749e434363f001e3ac259.png
dispatch
code:ts
dispatch(signUpUser(data));
ステート変更の意図を表明するだけのメソッド
アプリのどこからでもアクションを呼べるようにするために使う
useSelector
code: ts
const { abc } = useSelector(
(state: StoreState) => state.attr
)
Storeを定義
code:reducers/store.ts
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({
reducer: rootReducer,
middleware: TODO
})
// rootReducer -> combineReducersで、複数のreducerをまとめることもできる
export const rootReducer = combineReducers({
posts: postsReducer,
comments: commentsReducer,
users: usersReducer,
})
export default store
_app.tsxにProviderを定義
code:_app.tsx
...
return (
<Provider store={store}>
...
</Provider>
)
SliceとActionの定義
code:store/slice.ts
const initialState = {
value: 0,
} as CounterState
export const CounterSlice = createSlice({
name: 'counter',
initialState: initialState,
// 状態を更新する関数
reducers: {
increment: (state) => { state.value += 1 },
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
}
})
Dispatchする
code:ts
const handleClick = () => {
dispatch(incrementByAmount(1))
}