redux Cannot read properties of undefined

otter·2022년 5월 21일
0

상황

리덕스를 처음 공부하고 있는중, 초기 상태를 전달하는 과정에서 Cannot read properties of undefined 오류가 계속해서 나왔다.

const counterReducer = (state = { counter: 0, showCounter: true }, action) => {
  if (action.type === 'increment') {
    return {
      counter: state.counter + 1,
    };
  }

  if (action.type === 'increase') {
    return {
      conuter: state.counter + action.amount,
    };
  }

  if (action.type === 'decrement') {
    return {
      counter: state.counter - 1,
    };
  }
};

const store = createStore(counterReducer);
export default store;
  • 이렇게 간단한 스토어를 만들어 주었고 이를 컴포넌트에서 호출하는 것이였는데
  • dispatch 하지 않은 상황에서 초깃값만 전달하려고 했던 거였다.

해결

const counterReducer = (state = { counter: 0, showCounter: true }, action) => {
  if (action.type === 'increment') {
    return {
      counter: state.counter + 1,
    };
  }

  if (action.type === 'increase') {
    return {
      conuter: state.counter + action.amount,
    };
  }

  if (action.type === 'decrement') {
    return {
      counter: state.counter - 1,
    };
  }
  
  return state;
};

const store = createStore(counterReducer);
export default store;
  • 아무런 dispatch 없이 리듀서가 호출되면 디폴트로 현재상태를 출력하는 return 을 넣고 해결했다.
profile
http://otter-log.world 로 이사했어요!

0개의 댓글