首页 文章

使用多个redux为每个app用户存储一个

提问于
浏览
2

在本机应用程序中,我正在使用redux . 目前整个应用程序都有单个商店,我使用redux-persist将商店缓存到localstorage .

我的应用程序是用户名和密码保护,您必须创建帐户才能使用它 .

现在我想提供能力,以便我的用户可以在他的帐户之间切换 - 如果他有多个帐户 - . 这导致了很多麻烦,因为现在每次用户在帐户之间切换时我都必须清除存储并重置状态 .

所以我在考虑可能是我可以使用多个商店,每个用户一个?

例如,我的应用状态看起来像

{
  chat:{},
  highscores:{},
  gameHistory:{},
}

现在,如果用户有帐户,请说 User1@gmail.com 状态将填充他的数据 . 他的州将被保存到LocalStorage,

一旦他将帐户切换到 User2@gmail.com 现在我必须将应用程序重置为其initialState,然后以某种方式从localStorage加载User2状态

我不希望每次用户在帐户之间切换时,应用程序的状态都会丢失 .

所以我考虑可能在这种情况下,使用多个Redux商店是一个很好的选择,每个用户一个 .

有没有人有一个旨在被多个用户使用的应用程序?我们怎样才能在redux中做到这一点?

2 回答

  • 0

    我不认为每个用户都有一个商店是个好主意 . 看到这个答案:https://stackoverflow.com/a/33633850/3794660

    为什么不按用户ID命名缩减器中的数据?像这样的东西:

    {
      currentUserId: "1",
      chat:{ "1": { // Chats for user id 1 }, "2": { // Chats for user id 2 }},
      highscores:{ // Same structure as above },
      gameHistory:{ // Same structure as above },
    }
    

    切换用户帐户时,只需更新状态中的currentUserId即可 .

    我建议使用选择器来封装逻辑以从存储中读取数据 .

    获取当前帐户所有聊天记录的简单选择器可能如下所示:

    const getCurrUserId = state => state.currentUserId
    
    const getChats = state => {
       const userId = getCurrUserId(state);
       return state.chat[userId];
    }
    

    然后,在 mapStateToProps 中使用简单的getChats选择器将数据传递给组件 . 通过这种方式,您可以封装逻辑以从状态中检索数据,如果需要,您的组件可以自由地更改策略 .

  • 0

    以上的答案工作正常,但由于我使用的是ImmutableJs,因此拥有一个深层嵌套的对象真的很难处理 .

    所以我最终用user_id命名存储密钥 .

    所以现在当我切换用户时,我只是使用来自localStorage或AsyncStorage的这个specefic用户数据刷新整个商店 .

    我在一个简单的reducer中包装了rootReducer来处理这个问题 .

    function makeRootReducer(rootReducer){
     return function reducer(state, action){
       if(action.type==='SWITCH_USER'){
          //LOAD USER DATA..
          const data = JSON.parse(localStorage.getItem("store.user."+action.id)||"{}");
          return makeInitialData(data); //this just return initialData.
        }
        let newState = rootReducer(state, action);
        //simple save state to localStorage if state changed
        if(state !== newState)localStorage.setItem('store.user.'+state.user_id',JSON.stringify(newState);
        return newState;
      }
    
    }
    

相关问题