首页 > 解决方案 > TypeError:无法读取开关中未定义的属性“类型”(action.type)

问题描述

我第一次尝试关注 youtube 上关于 redux 的视频,但不知道为什么我得到了undefined。我已经尝试在谷歌上寻找答案,但仍然无法弄清楚。

 import { createStore } from 'redux';


  //action
  const up = () => {
    return { 
      type: 'up' 
    }
  }

  const down = () => {
    return { 
      type: 'down' 
    }
  }

  //reducer
  const counter = (state = 0, action) => {
    switch(action.type){
      case 'up':
        return state + 1;
      case 'down':
        return state - 1;
    }
  }
        
  let store = createStore(counter());

  store.subscribe(() => console.log(store.getState()))

  store.dispatch(up())
  store.dispatch(down())

谢谢您的帮助。

标签: reactjsredux

解决方案


您必须像这样传递实际函数createStore

  let store = createStore(counter);

这样,您将传递 的实际函数定义counter,而不仅仅是返回状态。


推荐阅读