react-redux 의 createAction, createReducer, createSlice 사용법

최하림·2022년 3월 13일
0

createAction(링크)공식문서
세부설명 자료(링크)
좀더 자세한 다른분의 최신 설명 자료 링크(클릭)

import { createAction } from '@reduxjs/toolkit';

기존함수

 export const addToDo = (text) =>{
     return{
         type : ADD,
         text
     }
 }
export const deleteToDo = (만세)=>{
    
     return{
         type:DELETE,
         id: 만세    
     } 
 }

createAction을 이용한 변경된 코드

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

액션 함수를 지우고 간결화 하고

payload 를 리듀서 함수에 넣는다.

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

각각
text:action.text 였지만 text 를빼고 payload 변경

action.id => action.payload

action 은 function 인 creacteAction 함수로 만들어진다

createReducer 사용법

기존 코드

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

변경 코드

const reducer = createReducer([],{
    [addToDo] : (state, action) => {
        const id = Date.now()
        state.push({text:action.payload, id:id});
    },
    [deleteToDo] : (state, action) =>{
        return(state.filter((toDo) => toDo.id !== action.payload) )
        // {} 가없으면 자동 리턴으로들어간다
    }
         
    
})

※ createReducer()에서는 새로운 state를 리턴하거나 state를 mutate할 수 있다.
※ 뭔가를 리턴할 때는 새로운 state여야만한다.


configureStore 사용법

기존 const store = createStore(reducer)

변경 const store = configureStore({reducer})

수정해주면 크롬에서 리덕스 툴 사용가능

그렇기 때문에 state 에 패스워드를 물어보면 안된다.


createSlice 사용법

액션과 리듀서 기능이 둘다 있는 함수이다.
createReducer 에서 좀더 변화한 방법이다.
좋은점은 다른곳으로 파는게(다른파일로 정보 보내기) 한번에 해서 좀더 편한느낌.

 const toDos = createSlice({
     name:'toDosReducer',
     initialState: [], // 기본 상태값
     reducers: { 
         add: (state, action) => {
                   const id = Date.now();
                     state.push({text:action.payload, id:id});
                    },
        remove: (state, action) =>{
         return(state.filter((toDo) => toDo.id !== action.payload) )
        }}
    })


const store = configureStore({reducer: toDos.reducer}) 
//이렇게 적어야 사용가능

export const {add, remove} = toDos.actions;
//기능을 다른곳으로 파는 것 - 추가가능

추가로 한줄이라도 줄이고싶다면

const store = configureStore({reducer: toDos.reducer})

export default store;

이것을

export default configureStore({reducer: toDos.reducer});

이렇게 줄일수도있다.

profile
노력하는 성장형

0개의 댓글