0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【備忘録】react-reduxを使ってカレンダーを切り替えられるようにする

Posted at

基本的な設計

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
});
  1. 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でsetNextMonthsetPreviousMonthをコールすればstoreのstateが変化する。
カレンダーを表示しているコンポーネントもstoreと接続するのを忘れないように。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?