如何将 redux 状态返回到初始状态

How to return redux state to initial state?

本文关键字:返回 初始状态 状态 redux      更新时间:2023-09-26

我很难弄清楚这一点,本质上我正在尝试将状态设置为初始状态,到目前为止我尝试过:

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

这只是将初始状态添加到现有状态


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

这将返回错误


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

这是将初始状态添加到现有的一个增益中


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

这有效,但我开始出现奇怪的突变错误。

Anders 提出的解决方案是正确的,但存在不可变的潜在问题。这将始终生成新对象。

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

请改用Jiri Fornous解决方案,因为这会改变您的数据。

更简单的方法是返回INITIAL_STATE。

case ACTIONS.RESET_STATE:
      return INITIAL_STATE;

如果你只是想完全重置状态,只需返回 INITIAL_STATE 的值:

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

如果要将INITIAL_STATE保存在一个地方。 将初始状态创建者更改为函数:

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