Why do I get “Reducer […] returned undefined during initialization” despite providing initialState to createStore()?

后端 未结 7 2266
死守一世寂寞
死守一世寂寞 2020-12-13 08:27

I had set InitialState in my redux createStore method ,and I corresponding InitialState as second arguments

I got a error in browser:

Un         


        
7条回答
  •  天命终不由人
    2020-12-13 08:52

    I just hit this same snag because I accidentally redefined state inside my reducer:

    const initialState = {
      previous: true,
      later: true
    }
    
    const useTypeReducer = (state = initialState, action) => {
      switch (action.type) {
        case 'TOGGLE_USE_TYPES':
          let state = Object.assign({}, state);   // DON'T REDEFINE STATE LIKE THIS!
          state[action.use] = !state[action.use];
          return state;
    
        default:
          return state;
      }
    }
    
    export default useTypeReducer;
    

    To fix the problem I needed to refrain from redefining state:

    const initialState = {
      previous: true,
      later: true
    }
    
    const useTypeReducer = (state = initialState, action) => {
      switch (action.type) {
        case 'TOGGLE_USE_TYPES':
          let _state = Object.assign({}, state);   // BETTER
          _state[action.use] = !state[action.use];
          return _state;
    
        default:
          return state;
      }
    }
    
    export default useTypeReducer;
    

提交回复
热议问题