简体   繁体   English

如何将状态重置为其初始状态?

[英]How do I reset the state to its initial state?

I can't seem to reset the default state; 我似乎无法重置默认状态; how do I do that? 我怎么做? I tried this but all it does is add state to state and calls it undefined. 我尝试了此操作,但它所做的只是将state添加到状态,并将其称为未定义。

const initialState = {
  name: null,
  coins: 0,
  image: null,
};

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case types.ADD_GROUP_COINS:
      return {
        ...state,
        coins: state.coins + action.coins
      };
    case types.DELETE_GROUP:
      return {
        state: undefined
      };
    default:
      return state;
  }
}

To reset the state to the initialState , simply return initialState , like this: 要将状态重置为initialState ,只需return initialState ,如下所示:

case types.DELETE_GROUP:
  return initialState;

Remember that in the reducer, the object that you return is the new state . 请记住,在化简器中,您返回的对象是新状态 You don't need to wrap it in another object, like this: 您无需将其包装在另一个对象中,如下所示:

return {
    state: ...
}

That will give you a property called state in your state, which isn't at all what you need. 这将为您提供一个名为state的属性,而这根本不是您所需要的。

From the documentation : 从文档中

The reducer is a pure function that takes the previous state and an action, and returns the next state. 减速器是一个纯函数,它采用上一个状态和一个动作,然后返回下一个状态。

It's easy to get confused about this, so be careful! 对此很容易感到困惑,所以要小心! Take a look at your default case if you're still not quite sure: you're returning the old state variable as the new state, not { state: state } which you are essentially doing with the current DELETE_GROUP handler. 如果您仍然不确定,请看一下default情况:您将旧的state变量作为新状态而不是 { state: state }作为新状态返回, 这实际上是使用当前的DELETE_GROUP处理程序进行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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