第一次使用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: ->...
答案 0 :(得分:0)
减速机必须:
如果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
操作并返回一个新的状态,并使用有效负载进行更新。