简体   繁体   中英

Redux - Reset state of subtree

What is the proper way to reset the subtree of a redux store? I'm not interested in resetting the entire redux store, but just the reducer subtree portion of it.

Here is an example snippet:

//initial state
const initialState = {
    isFetching: false,
    error: '',
    page: 0
}

//reducer for suggestions store
export default function suggestions (state = initialState, action) {
    switch (action.type) {
        case FETCHING_SUGGESTIONS : {
            return {
                ...state,
                isFetching: true
            }
        }
        case FETCHING_SUGGESTIONS_SUCCESS : {
            return {
                ...state,
                [action.suggestion.suggestionId] : action.suggestion
            }
        }
        case FETCHING_SUGGESTIONS_ERROR : {
            return {
                ...state,
                isFetching: false,
                error: "Error in fetching suggestions"
            }
        }
        case CHANGE_PAGE : {
            return {
                ...state,
                page: action.page
            }
        }
        case ADD_SUGGESTION : {
            return {
                ...state,
                [action.suggestion.suggestionId]: action.suggestion
            }
        }
        case CLEAR_SUGGESTIONS : {
            return {
                initialState
            }
        }
        default : 
            return state
    }
}

I would think this would work, however whenever the CLEAR_SUGGESTIONS action is dispatched, I suddenly get undefined props in some of my components and the following error: warning.js:36 Warning: performUpdateIfNecessary: Unexpected batch number (current 161, pending 157)

I'm not 100% confident I'm doing this correctly. Can someone confirm if the issue is with my reducer, or somewhere along my components lifecycle methods?

Thanks!

The object you create will look like this:

{
  initialState: {
    isFetching: false,
    error: '',
    page: 0
  }
}

What you want is this:

case CLEAR_SUGGESTIONS : {
  return {
    ...initialState
  }
}

You are accidentally nesting initialState under a key called 'initialState. You just want:

case CLEAR_SUGGESTIONS : {
  return initialState
}

There's no need to copy initialState, since store state is immutable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM