我尝试了简单的react,redux, AJAX 工作示例,并遵循Reddit API tutorial,但我无法创建store和get错误:
Uncaught Error: Expected the reducer to be a function.
index.jsx
...
import { createStore, applyMiddleware } from 'redux'
var thunkMiddleware = require('redux-thunk');
var createLogger = require('redux-logger');
var rootReducer = require('./reducers.js');
const loggerMiddleware = createLogger();
function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(
thunkMiddleware,
loggerMiddleware
)
)
}
const store = configureStore();
...
rootReducer.js
import { combineReducers } from 'redux';
function products(state = {
isFetching: false,
didInvalidate: false,
items: []
}, action) {
switch (action.type) {
case 'REQUEST_PRODUCTS':
return Object.assign({}, state, {
isFetching: true,
didInvalidate: false
})
case 'RECEIVE_PRODUCTS':
return Object.assign({}, state, {
isFetching: false,
didInvalidate: false,
items: action.posts,
lastUpdated: action.receivedAt
})
default:
return state
}
}
function specialPosts(state = { }, action) {
switch (action.type) {
case RECEIVE_SPECPOSTS:
case REQUEST_SPECPOSTS:
return Object.assign({}, state, {
req: true
})
default:
return state
}
}
const rootReducer = combineReducers({
products,
specialPosts
});
export default rootReducer;
rootReducer的类型是object,但为什么呢?我应该将createStore
函数更改为rootReducer.default
吗?
return createStore(
rootReducer.default,
initialState,
applyMiddleware(
thunkMiddleware,
loggerMiddleware
)
)
package.json
"redux-logger": "^2.6.1",
"react-redux": "^4.4.1",
"react-redux-provide": "^5.2.3",
"redux": "^3.3.1",
"redux-thunk": "^2.0.1",
8条答案
按热度按时间9o685dep1#
然后,初始状态将从各个reducer函数返回的初始状态自动创建。这些单独的状态可以作为
state.products
和state.specialPosts
访问z9gpfhce2#
问题是由于rootReducer被“require”(ES5)导入:
如果你通过ES6方法导入它,它会像你所期望的那样正确地将rootReducer.js的默认值自动保存到rootReducer中:
我看到你在那个文件中混合了ES5(require)和ES6(import)...我在我的项目中也混合了,这就是为什么我遇到了这个问题。更多信息可以在这里找到:https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0#.2x2p2dx3m
kgqe7b3p3#
创建存储时,第一个参数必须是函数,表示reduce(
()=>[]
)参数错误:
解决方案:
vojdkbi04#
当您看到错误时:
未捕获错误:期望reducer是一个函数
这并不一定意味着
reducer
不是一个函数。如果您遇到此错误,您应该尝试使用justreducer
创建存储。就像这样:createStore(reducer)
这可能是工作。
在我的例子中,第二个参数是错误的,因为我没有以正确的顺序调用
compose
和applyMiddleware
。所以这是一个正确的设置,似乎在我的情况下工作:fcipmucu5#
rootReducer
vtwuwzda6#
我使用VS Code Insiders,有时更改无法正确保存。因此,如果您遵循了以上所有的操作,错误仍然存在,请转到每个文件并按STRG+S。它为我解决了这个问题。
vxbzzdmp7#
我也遇到过同样的问题,它通过
我的
reducer
是x8goxv8g8#
当你看到这个错误:
Uncaught Error: Expected the reducer to be a function
时,必须确保在src/index.js文件中,createStore()
方法的第二个参数必须是函数。这是错误的:
const store = createStore(rootReducer, applyMiddleware)
此分类下一篇:
const store = createStore(rootReducer, applyMiddleware())
新更新请使用configureStore:
此分类下一篇:
const store = configureStore(rootReducer, applyMiddleware())