开发者社区> 问答> 正文

#React 如何在Redux中重置状态?

#React 如何在Redux中重置状态?

展开
收起
因为相信,所以看见。 2020-05-07 22:34:37 682 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    您需要在您的应用程序中编写一个根化约简器,将处理操作委托给由生成的约简器combineReducers()。

    例如,让我们采取行动rootReducer()后返回初始状态USER_LOGOUT。众所周知,无论以什么方式进行操作,都应将reducer undefined作为第一个参数调用时返回初始状态。

    const appReducer = combineReducers({
      /* your app's top-level reducers */
    })
    
    const rootReducer = (state, action) => {
      if (action.type === 'USER_LOGOUT') {
        state = undefined
      }
    
      return appReducer(state, action)
    }
    
    

    如果使用redux-persist,则可能还需要清洁存储设备。redux-persist将状态的副本保存在存储引擎中。首先,您需要导入适当的存储引擎,然后在将状态设置为undefined之前解析状态,并清除每个存储状态键。

    const appReducer = combineReducers({
      /* your app's top-level reducers */
    })
    
    const rootReducer = (state, action) => {
      if (action.type === 'USER_LOGOUT') {
        Object.keys(state).forEach(key => {
          storage.removeItem(`persist:${key}`)
        })
    
        state = undefined
      }
    
      return appReducer(state, action)
    }
    
    2020-05-07 22:35:49
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
利用编译将 Vue 组件转成 React 组件 立即下载
React Native 全量化实践 立即下载
React Native项目实战优化之路 立即下载