Redux store does not have a valid reducer

2019-02-04 10:02发布

问题:

Haven't been able to find anything around here regarding this error:

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

My reducer

export default function FriendListReducer(state = {friends : []}, action) {
  switch (action.type) {
    case 'ADD_FRIEND':
      return [
        { friends : action.payload.friend }, ...state.friends
      ]     
    default:
      return state;
  }
  return state;
}

Combiner

import { combineReducers } from 'redux';
import { FriendListReducer } from './FriendListReducer';

const rootReducer = combineReducers({
  friends: FriendListReducer
});
export default rootReducer;

My store config

import { applyMiddleware, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import rootReducer from '../reducers/reducers';

export default function configureStore(initialState = { friends: [] }) {
  const logger = createLogger({
    collapsed: true,
    predicate: () =>
    process.env.NODE_ENV === `development`, // eslint-disable-line no-unused-vars
  });

  const middleware = applyMiddleware(thunkMiddleware, logger);

  const store = middleware(createStore)(rootReducer, initialState);

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers/reducers', () => {
      const nextRootReducer = require('../reducers/reducers').default;
      store.replaceReducer(nextRootReducer);
    });
  }

  return store;
}

回答1:

Your import statement is incorrect. Either you use import { Foo } from 'bar' together with export Foo, or use import Foo from 'bar' if you export with export default Foo.

In other words, change either export default function FriendListReducer to export function FriendListReducer, or change the import statement from import { FriendListReducer } to import FriendListReducer.



回答2:

If the object is empty.

 export  default  combineReducers({

 })

This error will show.



回答3:

../reducers/reducers ? it's a strange naming

Anyway, it seems ../reducers/reducers doesn't return a reducer, if reducers is a directory, put a index.js inside, import each reducer and create a root reducer

import FriendListReducer from "./FriendListReducer"

const rootReducer = combineReducers({
   friendList : FriendListReducer
})

export default rootReducer

you will have state.friendList in your state.

I hope it will help



回答4:

It looks like your top-level reducer function is using an array as its default value. Redux expects that the very top of your state will be an object, not an array. Try putting the array at a particular key in that object, like { friendList : [] }.