How to return redux state to initial state?

别等时光非礼了梦想. 提交于 2019-12-10 10:27:36

问题


I'm having surprisingly difficult time figuring this out, essentially I'm trying to set state to initial state, so far I tried:

// -- Initial state ------------------------------------------------------------
const INITIAL_STATE = {
  search: {
    listings: []
  },
  listings: []
}

// -- Story structure for story editor -----------------------------------------
export default function(state = INITIAL_STATE, action) {
  switch(action.type) {
    case ACTIONS.RESET_STATE:
      return { ...state, INITIAL_STATE }
    default:
      return state;
  }
}

this just adds initial state to existing one


case ACTIONS.RESET_STATE:
      return { ...state, state = INITIAL_STATE }

this returns error


case ACTIONS.RESET_STATE:
      return { ...state, state: INITIAL_STATE }

this is adding initial state to existing one gain


case ACTIONS.RESET_STATE:
      return { ...state, search: { listings:[] }, listings: [] }

This works, but I start getting weird mutation errors.


回答1:


If you simply want to reset state completely, just return the value of INITIAL_STATE:

export default function(state = INITIAL_STATE, action) {
  switch(action.type) {
    case ACTIONS.RESET_STATE:
      return {
                 search: {
                     listings: []
                 },
                 listings: []
             };
    default:
      return state;
  }
}

If you want to keep the INITIAL_STATE in a single place. Change the initial state creator to a function:

function get_INITIAL_STATE => {
  return { search: {
               listings: []
           },
           listings: []
         }
}

export default function(state = get_INITIAL_STATE(), action) {
  switch(action.type) {
    case ACTIONS.RESET_STATE:
      return get_INITIAL_STATE();
    default:
      return state;
  }
}



回答2:


The proposed solution of Anders is right, but has potential problem with immutables. This generates always new object.

case ACTIONS.RESET_STATE:
    return { ...INITIAL_STATE };



回答3:


Look at Jiri Fornous solution instead, as this will mutate your data.

An even easier way is to just return INITIAL_STATE.

case ACTIONS.RESET_STATE:
      return INITIAL_STATE;


来源:https://stackoverflow.com/questions/35477202/how-to-return-redux-state-to-initial-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!