基本的な設計
storeには以下のような形のstateを登録する。
calendar:{
year: number;
month: number;
}
このオブジェクトを元にカレンダーを作成している。
カレンダーの月を切り替えるボタンを押すとactionがdispatchされ、storeの情報が更新される。それによりカレンダーを表示しているコンポーネントがレンダリングされ、表示が切り替わる。
1.actionの定義
export const CALENDAR_SET_MONTH = "calendar/monthChanged"
export const calendarSetMonth = (payload) => ({
type: CALENDAR_SET_MONTH,
payload
});
- reducerの定義
const day = dayjs(); //その日のdayjsオブジェクトを取得
const init = formatMonth(day); //別ファイルで定義した関数。dayを{month: number, year: number}の形に整形する。
const calendarReducer = (state = init, action) => {
const { type, payload } = action;
switch (type) {
case CALENDAR_SET_MONTH:
return payload;
default:
return state;
}
}
export default calendarReducer;
今後、別のreducerを作成する予定なので別のファイルでcombineReducersをしておく。
const rootReducer = combineReducers({calendar: calendarReducer});
トップのコンポーネントでstoreに登録しておく。
2.presentational componentとの接続
const EnhancedPresentation = () => {
const month = useSelector((state) => state.calendar);
const nextMonth = getNextMonth(month); //次の月を取得する関数。別ファイルで定義済み。
const previousMonth = getPreviousMonth(month); //前の月を取得する関数。別ファイルで定義済み。
const dispatch = useDispatch();
return (
<Presention
setNextMonth = {() => dispatch(calendarSetMonth(nextMonth))}
setPreviousMonth = {() => dispatch(calendarSetMonth(previousMonth))}
/>
)
}
あとはpresentational componentでsetNextMonth
とsetPreviousMonth
をコールすればstoreのstateが変化する。
カレンダーを表示しているコンポーネントもstoreと接続するのを忘れないように。