How to return redux state to initial state?

醉酒当歌 提交于 2019-12-05 18:57:15

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;
  }
}

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 };

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