거북이개발자

[Redux] Redux Toolkit 본문

Redux

[Redux] Redux Toolkit

류정식 2021. 2. 26. 03:39

0. 설 치

 

npm install @reduxjs/toolkit

 

 

 

 

1. CreateAction

 

(1)

const ADD="ADD";
const DELETE="DELETE";

const addToDo = text => {
    return {
      type: ADD,
      text
    };
  };
  
  const deleteToDo = id => {
    return {
      type: DELETE,
      id: parseInt(id)
    };
  };

r기존의 위의 코드를

const addToDo=createAction("ADD");
const deleteToDo=createAction("DELETE");

이렇게 변경할 수 있다.

 

 

(2)

console.log(addToDo(), deleteToDo());

    두 함수를  console.log 해보면  

 

이렇나 값을 리턴하는것을 볼 수 있다.

 

(3)

  const reducer = (state = [], action) => {
    switch (action.type) {
      case addToDo.type:
        return [{ text: action.payload, id: Date.now() }, ...state];
      case deleteToDo.type:
        return state.filter(toDo => toDo.id !== action.payload);
      default:
        return state;
    }
  };

  reducer함수가 이렇게 변경해 준다.

우선 case에서 addToDo.type을 이용해준다.

또한 text, id대신 action.playload를 이용한다.

 

 

 

 

 

2. CreateReducer

  const reducer = (state = [], action) => {
    switch (action.type) {
      case addToDo.type:
        return [{ text: action.payload, id: Date.now() }, ...state];
      case deleteToDo.type:
        return state.filter(toDo => toDo.id !== action.payload);
      default:
        return state;
    }
  };

기존의 위의 reducer 함수를

 

const reducer=createReducer([], {

  [addToDo]:(state, action)=>{
    state.push({ text: action.payload, id: Date.now() });
  },
  [deleteToDo]:(state, action)=>{
    state.filter(toDo => toDo.id !== action.payload);
  }
})

이렇게 작성가능하다.

여기서 중요한 점은 기존 reducer와 다르게 push를 통해서 state를 mutate 해준다.

 

 

 

 

3. ConfigureStore

const store=configureStore({reducer});

store생성 시 configureStore로 생성시 

위와 같은 developer tool을 이용할 수 있다.

 

 

 

 

 

4. CreateSlice

const addToDo=createAction("ADD");
const deleteToDo=createAction("DELETE");

const reducer=createReducer([], {

  [addToDo]:(state, action)=>{
    state.push({ text: action.payload, id: Date.now() });
  },
  [deleteToDo]:(state, action)=>{
    state.filter(toDo => toDo.id !== action.payload);
  }
})

 

그동안의 위의코드를  createSlice를 사용해서 더 줄일 수 잇따.

 

const toDos = createSlice({

  name: 'toDosReducer',
  initialState: [],
  reducers: {
    add: (state, action) => {
      state.push({ text: action.payload, id: Date.now() });
    },
  
    remove: (state, action) => 
      state.filter(toDo => toDo.id !== action.payload)
  }
});

const store = configureStore({ reducer:toDos.reducer });
 export const{  add,  remove }=toDos.actions;

이렇게 더욱 간결하게 사용 가능하다.

Comments