ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 개선사항
    Redux 2022. 7. 27. 20:31

    reducer함수에서 action을 사용할 때, if말고 switch를 사용할 수 있다.

    const countModifier = (count = 0, action) => {
        // if (action.type === "ADD") {
        //     return count + 1;
        // } else if (action.type === "MINUS") {
        //     return count - 1;
        // } else {
        //     return count;
        // }
        switch (action.type) {
            case "ADD":
                return count + 1
            case "MINUS":
                return count - 1 
            default:
                return count
        }
    }

     

    그리고, action type에서 string으로 작성하게 되면 "MNUS"이렇게 마이너스 오타가 생겨도 모르게 된다. 그래서 변수를 사용할 수 있다.

    const ADD = "ADD";
    const MINUS = "MINUS";
    
    const countModifier = (count = 0, action) => {
        switch (action.type) {
            case ADD:
                return count + 1
            case MINUS:
                return count - 1 
            default:
                return count
        }
    }
    
    const countStore = createStore(countModifier);
    
    const handleAdd = () => {
        countStore.dispatch({ type: ADD })
    }
    const handleMinus = () => {
        countStore.dispatch({ type: MINUS })
    }

    이런 식으로, 변수를 사용하면 에러가 났을 때, 변수에 에러가 생긴걸 쉽게 알 수 있다.

    'Redux' 카테고리의 다른 글

    mapStateToProps와 mapDispatchToProps  (0) 2022.07.28
    리덕스만으로 todo 만들기  (0) 2022.07.27
    subscribe  (0) 2022.07.27
    action  (0) 2022.07.27
    store 와 reducer  (0) 2022.07.27

    댓글

Designed by Tistory.