Redux报错:Expected the reducer to be a function 技术求助
Hey there! That error Error: Expected the reducer to be a function is super common when setting up Redux, and it almost always boils down to one key issue: the rootReducer you're passing to createStore isn't actually a valid function. Let's break down how to fix this step by step, using your code as reference.
1. Make sure your rootReducer is properly defined
Redux reducers must always be functions that take state and action as arguments and return a new state. The most common mistake here is forgetting to use combineReducers when you have multiple slice reducers.
❌ Wrong way (not a function):
// reducers/index.js (bad example) import userReducer from './userReducer'; import postsReducer from './postsReducer'; // This is an object, not a reducer function! const rootReducer = { user: userReducer, posts: postsReducer }; export default rootReducer;
✅ Correct way (using combineReducers):
// reducers/index.js import { combineReducers } from 'redux'; import userReducer from './userReducer'; import postsReducer from './postsReducer'; // combineReducers returns a single reducer function const rootReducer = combineReducers({ user: userReducer, posts: postsReducer }); export default rootReducer;
2. Verify you're importing rootReducer correctly in configureStore
If you exported rootReducer as a default export, make sure you're importing it without curly braces. Mixing up default and named imports will result in importing undefined (or an invalid value) instead of the reducer function.
❌ Wrong import:
// store/configureStore.js (bad example) // This tries to import a named export called rootReducer, but you used default export import { rootReducer } from './reducers';
✅ Correct import:
// store/configureStore.js import rootReducer from './reducers'; // Default import matches default export
3. Double-check your configureStore implementation
Ensure your configureStore function is properly creating and returning the store. Based on your code snippet, here's a corrected full version:
// store/configureStore.js import { createStore } from 'redux'; import { devToolsEnhancer } from 'redux-devtools-extension'; import rootReducer from './reducers'; // Confirm this import is correct const initialState = { // Define your app's initial state here (match your reducer structure) }; const configureStore = () => { const store = createStore( rootReducer, // This must be a valid function now initialState, devToolsEnhancer() ); return { store }; // Matches how you're destructuring it in index.js }; export default configureStore;
Quick recap of what went wrong
The error is thrown because createStore expects its first parameter to be a reducer function, but your rootReducer was either an object, undefined, or some other non-function value. Fixing the definition and import of rootReducer should resolve this immediately.
内容的提问来源于stack exchange,提问作者victor.ja

