redux Store没有有效的reducer coffeescript

时间:2016-07-20 04:59:33

标签: javascript coffeescript ecmascript-6 redux

第一次使用Redux并且我理解了Actions和Reducers的概念,但无法让它们在我的代码中很好地发挥,我担心这是因为我使用的是CoffeeScript而不是ES6。

认为问题是我无法在 /app/reducers/index.coffee 中执行export default ...但是老实说Redux对于我和我一直在和webpack一起磕磕绊绊并且反应一段时间,但我仍然不是最舒服的,所以¯\ _ _(ツ)_ /¯

我一直收到错误:

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

/app/actions/index.coffee

{ FETCH_ITEMS, FETCH_SINGLE_ITEM } = require('../constants')

fetch_items = ->
  { type: FETCH_ITEMS }


fetch_single_item = (id) ->
  {
    type: FETCH_SINGLE_ITEM,
    id: id
  }

module.exports = { fetch_items, fetch_single_item }

/app/reducers/items.coffee

$ = require('jquery')
{ FETCH_ITEMS, FETCH_SINGLE_ITEM } = require('../constants')
{ fetch_items } = require('../actions')

INITIAL_STATE = []

items = (state=INITIAL_STATE, action) ->
  console.log action.type
  switch action.type
    when FETCH_ITEMS
      console.log 'FETCH_ITEMS'
      $.get "http://dosomething.com/items", (resp) ->
        console.log resp
    when FETCH_SINGLE_ITEM
      console.log 'do something'
    else
      console.log "suckit turk!"
  state

module.exports = { items }

/app/reducers/index.coffee

{ combineReducers } = require('redux')
items = require('./items')

reducers = combineReducers({ items })

module.exports = { reducers }

最后 /app/index.cjsx

React        = require("react")
ReactDOM     = require("react-dom")
{
  createStore,
  combineReducers,
  appyMiddleware
} = require('redux')

{ reducers } = require("./reducers/")

STORE = createStore combineReducers({ reducers, routing: routerReducer     })
HISTORY = syncHistoryWithStore(browserHistory, STORE)

STORE.subscribe () ->
  console.log STORE.getState()

...omitted react render: ->...

修改

对不起大家,是的routeReducer是定义的,我只是省略了它,因为我很确定这不是问题。

/app/index.cjsx

React        = require("react")
ReactDOM     = require("react-dom")
{
  createStore,
  combineReducers,
  appyMiddleware
} = require('redux')

{
  syncHistoryWithStore,
  routerReducer
} = require('react-router-redux')


{ reducers } = require("./reducers/")

STORE = createStore combineReducers({ reducers, routing: routerReducer     })
HISTORY = syncHistoryWithStore(browserHistory, STORE)

STORE.subscribe () ->
  console.log STORE.getState()

...omitted react render: ->...

1 个答案:

答案 0 :(得分:0)

减速机必须:

  1. 接收状态和操作作为参数
  2. 始终返回相同或新的状态。
  3. 如果items语句中的所有情况都不匹配,则“reducer”switch似乎只返回状态,这意味着它不是有效的reducer。如果在发出其中一个操作时遇到此错误,redux可能会检测到尚未返回新状态。在items使用适当的减速器后,查看是否仍然遇到此问题。

    旁注

    您正在从items reducer进行异步API调用,而您的存根代码看起来就像是计划添加第二个。这不是减速器的正确使用;商店应该保存与您的应用程序状态相关的数据,并且减速器应该在给定旧状态和操作类型和/或有效负载的情况下制造新状态。

    相反,在“动作创建者”中调用这些异步函数。 (See docs.)

    fetch_items之类的动作创建者将执行AJAX请求,并在成功时触发set_items动作的发送,例如{ type: 'SET_ITEMS', payload: [...response.items...] }。您的reducer将侦听SET_ITEMS操作并返回一个新的状态,并使用有效负载进行更新。