Redux派遣动作

时间:2020-03-23 12:26:42

标签: redux

当我使用命令节点索引时,我只是尝试运行一个简单的redux程序,它向我显示错误,表明操作必须是普通对象,这是我的代码

const redux = require('redux')
const createStore = redux.createStore
const BUY_CAKE = 'BUY_CAKE'
function buyCake () {
  return
  {
    type: BUY_CAKE
  }
}

const initialState = {
  numOfCakes: 10
}

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case BUY_CAKE: return {
      ...state,
      numOfCakes: state.numOfCakes - 1
    }
    default: return state
  }
}

const store = createStore(reducer)
console.log("initial state is ", store.getState())
const unsubscribe = store.subscribe(() => console.log("updated", store.getState()))
store.dispatch(buyCake())
store.dispatch(buyCake())
store.dispatch(buyCake())
store.dispatch(buyCake())
unsubscribe()

当我dispatch(buyCake())时,它仅显示错误,但是如果我确实存储.dispatch({type:BUY_CAKE}),则代码运行良好,为什么会发生错误

1 个答案:

答案 0 :(得分:0)

因为您的return语句格式错误。请注意此致命功能:

JavaScript将自动插入分号。如果没有括号,JavaScript将忽略以下各行,并返回不带任何值的

这是您的带有分号的函数,它将返回undefined

function buyCake(){
return;
{
type:BUY_CAKE
};
};

解决方案:将大括号移到return行:

function buyCake(){
  return {
      type: BUY_CAKE
    }
}