Redux: Unexpected key found in preloadedState argument passed to createStore

前端 未结 3 1058
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 21:46

Can you help me with exception Unexpected key \"userName\" found in preloadedState argument passed to createStore. Expected to find one of the known reducer keys inste

相关标签:
3条回答
  • 2021-01-03 21:49

    Or just:

    import yesReducer from './yesReducer';
    
    const store = createStore(combineReducers({
        yesReducer,
        noReducer: (state = {}) => state,
    });
    
    0 讨论(0)
  • 2021-01-03 21:57
    import * as reducers from './reducers'
    

    is a good technique to avoid having your core code depend on the various functionalities implementations.

    In order to make it work, you have to specify the name of the reducer to be the same as your store key userName. This can be achieved this way:

    In the index.js that sits in the reducers folder, do

    export { userNameReducer as userName } from "./UserNameReducer"
    export { otherReducer as other } from "./OtherReducer"
    

    An other way would be to directly rename the exported reducer the same as the store key.

    0 讨论(0)
  • 2021-01-03 22:10

    TLDR: stop using combineReducers and pass your reducer to createStore directly. Use import reducer from './foo' instead of import * from './foo'.

    Example with default import/export, no combineReducers:

    // foo.js
    function reducer(state, action) { return state; }
    export default reducer;
    
    ----
    
    // index.js
    import myReducer from './foo';
    

    Example with combineReducers

    // foo.js
    export default (state, action) => { ... }
    
    ----
    
    // bar.js
    export default (state, action) => { ... } 
    
    ----
    
    // index.js
    import foo from './foo';
    import bar from './bar';
    
    const store = createStore(combineReducers({
        foo,
        bar,
    });
    

    The second argument of createStore (preloaded state) must have the same object structure as your combined reducers. combineReducers takes an object, and applies each reducer that is provided in the object to the corresponding state property. Now you are exporting your reducer using export default, which is transpiled to something like module.exports.default = yourReducer. When you import the reducer, you get module.exports, which is equal to {default: yourReducer}. Your preloaded state doesn't have a default property thus redux complains. If you use import reducer from './blabla' you get module.exports.default instead which is equal to your reducer.

    Here's more info on how ES6 module system works from MDN.

    Reading combineReducers docs from redux may also help.

    0 讨论(0)
提交回复
热议问题