[TIL] 20211001


Paletteプロジェクトはredux-toolkit + redux-sagaを用いて状態管理を行うことにした.
redux-sagaは就職の挑戦です(...)勉强するためには、强制的に勉强しますが、全然勉强したことがないので、勉强しなければなりません.
ふと実戦種目をした時のことを思い出した.
もう1組のフロントの同級生はredux-toolkitを書かなければならないと言っていましたが、コード量も減り、勉強に10分しかかかりませんでした.とてもお勧めしました.
しかし、その時のプロジェクトの時間は半分以上過ぎた.
私たちのコードはもう膨大です.
実装するコードがたくさんあります😂😂😂
だから今日は残されたredux-toolkitに触れました.
明日は勉強が必要かもしれませんが、整理しておきます.
Redux-toolkit
インストール
yarn add @reduxjs/toolkit
ショップの作成
既存
import { createStore, combineReducer } from "redux";
import counter from "./module/counter";

const rootReducer = combineReducer({
	counter,
});

const store = createStore(rootReducer);

export default store;
redux-toolkitの使用
import { configureStore } from "@reduxjs/toolkit";
import counter from "./module/counter";

export default configureStore({
	reducer: {
		counter,
	}
})
Reducer(action type、action creator、reduce)の作成
既存
以前はaction type、action creator、initialstate、reduceを別々に作成する必要がありました.
// action type
const INCREMENT = "counter/INCREMENT";
const DECREMENT = "counter/DECREMENT";
const INCREMENT_BY_AMOUNT = "counter/INCREMENT_BY_AMOUNT";
const DECREMENT_BY_AMOUNT = "counter/DECREMENT_BY_AMOUNT";

// action creator
export const increment = () => ({type: INCREMENT});
export const decrement = () => ({type: DECREMENT});
export const incrementByAmount = (num) => ({type: INCREMENT_BY_AMOUNT, payload: {num}});
export const decrementByAMount = (num) => ({type: DECREMENT_BY_AMOUNT, payload: {num}});

// initialState
const initialState = {
	count: 0,
};

// reducer
const counter = (state = initialState, action) => {
	switch(action.type) {
		case INCREMENT:
			return {...state, count: state.count++};
    case DECREMENT:
			return {...state, count: state.count--};
    case INCREMENT_BY_AMOUNT:
			return {...state, count: state.count + action.payload.num};
		case DECREMENT_BY_AMOUNT:
		  return {...state, count: state.count - action.payload.num};
		default:
			return state;
	}
}

export default counter;
redux-toolkitの使用
Actiontype、action createoreを作成する必要はありません🙂
Initialstateは内部設定でも外部設定でも使用できます.
import { createSlice } from "@reduxjs/toolkit";

// slice
const counterSlice = createSlice({
	// name과 reducers가 결합되어 action type이 "counter/increment"와 같이 생성된다.
	name: "counter",
	initialState: {
		count: 0,
	},
	reducers: {
		increment(state) {
			state.count++;
		},
		decrement(state) {
			state.count--;
		},
		incrementByAmount(state, action) {
			state.count += action.payload;
		},
		decrementByAmount(state, action) {
			state.count -= action.payload;
		}
	}
});

// action creator 들은 만든 slice.actions로 export 해주면 된다.
export { increment, decrement, incrementByAmount, decrementByAmount } = counterSlice.actions;
// reducer도 slice.reducer로 뽑아내서 export 해준다.
export default counterSlice.reducer;