효율적인 Redux 개발을 위한 도구모음
=> 코드를 더 좋고 유지보수하기 쉽게 만들기 위해 사용
// redux/config/configStore.js
import { combineReducers, createStore } from "redux";
import todolists from "../modules/todolist";
const rootReducer = combineReducers({
todolists,
});
const store = createStore(rootReducer);
export default store;
// redux/modules/todolist.js
// 액션
const ADD_LIST = "ADD_LIST";
const DELETE_LIST = "DELETE_LIST";
const CHANGE_LIST = "CHANGE_LIST";
const PLUS_COUNT = "PLUS_COUNT";
// 액션 크리에이터
export const addList = (payload) => {
return {
type: ADD_LIST,
payload,
};
};
export const deleteList = (payload) => {
return {
type: DELETE_LIST,
payload,
};
};
export const changeList = (payload) => {
return {
type: CHANGE_LIST,
payload,
};
};
export const plusCount = (payload) => {
return {
type: PLUS_COUNT,
payload,
};
};
// 초기값
const initialState = {
lists: [
{
id: 1,
title: "이거해야함",
desc: "이거는 이렇고 저거는 저렇고",
isDone: false,
},
{
id: 2,
title: "저거해야함",
desc: "저거는 저렇고 이거는 이렇고",
isDone: true,
},
],
number: 3,
};
// 리듀서
const todolists = (state = initialState, action) => {
switch (action.type) {
case ADD_LIST:
return {
...state,
lists: [...state.lists, action.payload],
};
case DELETE_LIST:
return {
...state,
lists: state.lists.filter((list) => list.id !== action.payload),
};
case CHANGE_LIST:
return {
...state,
lists: state.lists.map((list) => {
if (list.id === action.payload) {
return { ...list, isDone: !list.isDone };
} else {
return { ...list };
}
}),
};
case PLUS_COUNT:
return {
...state,
number: state.number + action.payload,
};
default:
return state;
}
};
export default todolists;
// redux/config/configStore.js
import { configureStore } from "@reduxjs/toolkit";
import todos from "../modules/todoSlice";
const store = configureStore({
reducer: todos,
});
export default store;
// redux/modules/todoSlice.js
import { createSlice } from "@reduxjs/toolkit";
// 초기값
const initialState = {
lists: [
{
id: 1,
title: "이거해야함",
desc: "이거는 이렇고 저거는 저렇고",
isDone: false,
},
{
id: 2,
title: "저거해야함",
desc: "저거는 저렇고 이거는 이렇고",
isDone: true,
},
],
number: 3,
};
// 액션 + 액션 크리에이터 + 리듀서
const todosSlice = createSlice({
name: "todos",
initialState,
reducers: {
addList: (state, action) => {
state.lists.push(action.payload);
},
deleteList: (state, action) => {
const newLists = state.lists.filter((list) => list.id !== action.payload);
state.lists = newLists;
},
changeList: (state, action) => {
const newLists = state.lists.map((list) => {
if (list.id === action.payload) {
return { ...list, isDone: !list.isDone };
} else {
return { ...list };
}
});
state.lists = newLists;
},
plusNumbers: (state, action) => {
state.number += action.payload;
},
},
});
export const { addList, plusNumbers, deleteList, changeList } = todosSlice.actions;
export default todosSlice.reducer;
위와 같이 툴킷이 훨씬 짧고 간결하여 좀 더 유지보수가 쉽다