[React-Redux] Cannot destructure property '' of ‘

Mark·2022년 8월 23일
1
post-thumbnail

문제 상황

  • store에 모듈 연결이 제대로 안 되어 있어서 발생하는 문제로 확인 됨

문제 원인

  • store에 연결한 리듀서 함수명이 다르거나, useSelector로 상태값을 조회하고자 할 때 export시키고 store에 연결한 함수명(리듀서)와 같이 않아서 발생한 에러로 확인됨

해결 방법

1. 모듈파일에서 리듀서 확인

  • todos_list라는 리듀서 함수를 생성했다.
  • export default todos_list : 내보내기 할 때 리듀서 함수를 해줘야 함
// Reducer
const todos_list = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TODO:
      return {
        ...state, // 상태값은 불변 객체로 관리해야 하므로 수정할 때마다 전개연산자를 활용해 새로운 객체를 생성한다.
        todos: state.todos.concat(action.todo),
      };

    case DELETE_TODO:
      return {
        ...state,
        todos: state.todos.filter((todo) => todo.id !== action.id),
      };
    case CHECK_TODO:
      return {
        ...state,
        todos: state.todos.map((todo) =>
          todo.id === action.id ? { ...todo, isDone: !todo.isDone } : todo
        ),
      };
    default:
      return state;
  }
};

// export default reducer
export default todos_list;

2. 모듈, 스토어 연결 확인 (여기서 부터 중요)

  • 위에서 export default 시킨 todo_list 함수명을 가진 리듀서를 가져와야 함(중요)
  • 여기서 export dafaulut 시킨 함수명으로 가져와야 함
// config > configStore.js
import { createStore } from "redux";
import { combineReducers } from "redux";
import todos_list from "../modules/todos";
// import todos from "../modules/todos";

const rootReducer = combineReducers({
  todos_list, // 모듈을 스토어와 연결
});
const store = createStore(rootReducer);

export default store;

3. useSelector로 조회하기

  • state에 접근할 때 state.[리듀서 함수명]으로 접근해야 함
  • 나의 경우 todos_list라는 함수명으로 export 시켜주고 스토어와 연결했기 때문에 state.todos_list로 접근해야지 에러 발생 안함
  • { todos } : state.todos_list가 가진 todos라는 객체를 구조분해 할당을 통해 그 필드를 가져온다는 의미
const { todos } = useSelector((state) => state.todos_list); // todos_list라는 이름을 가진 리듀서에 접근해서 todos객체를 가져오는 것
profile
개인 공부 정리

0개의 댓글