【问题标题】:Resetting store to initialState is not working将存储重置为 initialState 不起作用
【发布时间】:2018-07-06 03:54:45
【问题描述】:

我正在使用 Redux 和 redux-storage 构建一个 ReactJS 应用程序

我需要一个可以将 store 重置为初始状态的按钮,所以我这样编写了 reducer:

const initialState={...}

export default function ProfilationSelectReducer (state=initialState, action){
 switch(action.type){
 ...
 case ProfilationSelectActionTypes.CLEAR_STORE:{

            return initialState
        }
 ...
 }
}

现在,此代码在应用程序的一个页面中工作,但在其他页面中,initialState 看起来正在更改(尽管是一个常量),导致不清除状态。

对这种行为有任何想法吗?如果需要更多信息,我很乐意与您分享

【问题讨论】:

  • 您能否分享代码(您如何调用 clear store 操作)和控制台输出的状态在哪些页面不起作用?
  • 值得注意的是,声明为 const 的变量仍然是可变的。 const 仅防止对象被重新分配 (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)。
  • 您是否尝试过在 const 变量上使用 deepFreeze 库来查看您的 reducer 函数是否是纯函数?

标签: javascript reactjs redux


【解决方案1】:

我发现关注这篇文章: https://stackoverflow.com/a/35477308/8608574

我将 initialState 的声明更改为函数。这是我现在的代码:

function getInitialState(){
 return{...}
}

export default function ProfilationSelectReducer (state=getInitialState(), action){
 switch(action.type){
 ...
 case ProfilationSelectActionTypes.CLEAR_STORE:{
        return getInitialState()
    }
 ...

 }
}

感谢大家的帮助

【讨论】:

    【解决方案2】:

    那些其他页面可能会在加载时调用更新商店的操作。使用 redux 开发工具查看您的商店是如何更新的。我不能推荐它,节省工作和时间。

    【讨论】:

      猜你喜欢
      • 2023-01-15
      • 2022-11-28
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2017-08-24
      • 2016-12-13
      相关资源
      最近更新 更多