Redux Toolkit

류슬기·2021년 4월 22일
0

TIL

목록 보기
13/16
post-thumbnail

Redux Toolkit

Creating a slice requires a string name to identify the slice, an initial state value, and one or more reducer functions to define how the state can be updated. Once a slice is created, we can export the generated Redux action creators and the reducer function for the whole slice

FSA(Flux Standard Actions)

액션 생성자는 type과 payload를 포함하여 액션을 생성

createSlice()

A function that accepts an initial state, an object full of reducer functions, and a "slice name", and automatically generates action creators and action types that correspond to the reducers and state.

슬라이스는 이름, 초기상태, 리듀서로 이루어진 객체
createAction()과, createReducer()가 합쳐진 형태

// redux toolkit boilerplate
import {createSlice} from '@reduxjs/toolkit';

const sliceReducer = createSlice({
	name : '',
	initialState: {},
	reducers: {}
});

// 구조분해할당
const {actions, reducer} = sliceReducer
export {} = actions;
export default reducer;

TodoList 예제

구조

📦src
┣ 📂todo
┃ ┣ 📂component
┃ ┃ ┣ 📜AddTodo.js
┃ ┃ ┣ 📜DeleteTodo.js
┃ ┃ ┣ 📜DoneTodo.js
┃ ┃ ┣ 📜EditTodo.js
┃ ┃ ┣ 📜Todo.js
┃ ┃ ┗ 📜Todos.js
┃ ┣ 📂container
┃ ┃ ┗ 📜TodoApp.js
┃ ┣ 📂reducer
┃ ┃ ┗ 📜todo.slice.js
┃ ┣ 📂service
┃ ┃ ┗ 📜Todo.service.js
┃ ┣ 📂style
┃ ┃ ┗ 📜Todo.css
┃ ┗ 📜index.js
┣ 📜App.js
┗ 📜index.js

reducer

const initialState = {
  todolist: [],
};

const todoSlice = createSlice({
  name: 'todoSlice',
  initialState,
  reducers: {
    editTodo(state, { payload }) {
      console.log('edit todo');
      const editId = state.todolist.find((todo) => todo.id === payload);
      editId.text = payload.text;
    },
    addTodo(state, { payload }) {
      state.todolist.push({ id: uuid(), text: payload, done: false });
    },
    toggleTodo(state, { payload }) {
      const toggle = state.todolist.find((todo) => todo.id === payload);
      toggle.done = !toggle.done;
    },
    allDeleteTodo(state, { payload }) {
      state.todolist.splice(payload);
    },
    deleteTodo(state, { payload }) {
      const idx = state.todolist.findIndex((todo) => todo.id === payload);
      state.todolist.splice(idx, 1);
      /*
            *********filter 사용하는 방법**********
            state.todolist = state.todolist.filter(
                (todo) => todo.id !== payload
            );
            */
    },
  },
});

reducer는 순수함수이기 때문에 Immutable해야 함
그래서 initialState를 해치치 않고 새로운 state를 리턴

container

부모 컴포넌트 -> 자식 컴포넌트 : 버블링
자식 컴포넌트 -> 부모 컴포넌트 : 캡쳐링

useSelector를 통해 reducer의 state를 구독하는 리스너 생성
상태를 props로 전달
-> Todo.js, Todos.js에서는 전달받은 props를 배열함수 map을 사용해서 값 할당

component


이벤트가 실행되면 ready였던 프로세스가 running되어야 하기 때문에 dispatch를 사용
dispatch()안에는 action메소드가 들어있는데 reducer에서 선언되어있던 action을 실행

profile
FE Developer🌱

0개의 댓글