【问题标题】:Redux store changes when reload page重新加载页面时 Redux 存储更改
【发布时间】:2018-07-02 18:45:01
【问题描述】:

我正在使用 react redux 实现两种不同类型的用户登录。 这是我的登录方式:

export const login = (credentials) => (dispatch) =>
    api.user.login(credentials).then(user => {
      localStorage.userJWT = user.token;
      localStorage.userEmail = user.email;
      localStorage.userId = user.id;
      localStorage.surname = user.surname;
      localStorage.type = user.type;
      dispatch(userLoggedIn(user));
});
  1. 对于第一类用户,我从后端返回:token、email、id、surname。
  2. 对于第二种用户,我从后端返回:token、email、id、type。

我做了一些第二类用户无法访问的安全路由。 所以如果返回变量surname,我为那个用户定义了具体的路由。

如果返回 type 变量,它会正确显示链接和 redux 存储中的所有内容。但是,如果我重新加载页面,它会自动将变量 type 更改为 undefined surname

这是我试图将 redux 状态保存在 store 中的地方,即使我重新加载页面也是如此。 常量存储 = 创建存储( 根减速器, composeWithDevTools(applyMiddleware(thunk)) );

 if(localStorage.userJWT && localStorage.userEmail && localStorage.userId && localStorage.type){
   const user = { token: localStorage.userJWT, email: localStorage.userEmail, id: localStorage.userId, type: localStorage.type};
   store.dispatch(userLoggedIn(user));
 }
 if(localStorage.userJWT && localStorage.userEmail && localStorage.userId && localStorage.surname){
   const user = { token: localStorage.userJWT, email: localStorage.userEmail, id: localStorage.userId, surname: localStorage.surname};
   store.dispatch(userLoggedIn(user));
 }

您能否建议为什么它不遵循我的 if 语句。 提前谢谢你。

【问题讨论】:

标签: reactjs redux store


【解决方案1】:

Redux 存储/状态在重新加载时重新初始化。您可以将您的身份验证信息保存在本地存储中,然后将其拉出以用作您的初始状态。这样,您的 Redux 状态将始终具有该身份验证信息,即使在重新加载时也是如此。

function reducer (state = initState(), action) {
    return state
}

function initState () {
    return { 
        token: localStorage.userJWT, 
        email: localStorage.userEmail, 
        id: localStorage.userId, 
        surname: localStorage.surname
    }
}

或者,如果你想在重新加载时保持整个 Redux 状态,你可以尝试实现一些包,比如redux-persist

【讨论】:

  • 我有减速器来保存状态。问题是它只使用token, email, id, surname 保存状态,但在重新加载期间将token, email, id, type 覆盖为token, email, id, surname
  • 我想我不明白这个问题。您是说您正在从本地存储中提取这些内容并在重新加载时分派 userLoggedIn 操作,但是键不正确?听起来您的实际减速器功能或 userLoggedIn 动作创建者有问题。可以发一下吗?
  • 我还刚刚注意到您的示例中有两个 if 块,没有 else。也许您的问题是第一个(带有类型)被调度,然后第二个(带有姓氏)被调度。根据您设置减速器的方式,您可能只是覆盖了第一次调度的所有内容。
  • 你知道吗,它被覆盖了,所以当我将else 添加到if statement 时,它开始工作。谢谢
猜你喜欢
  • 2015-11-13
  • 2015-03-29
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 2021-05-17
  • 2021-02-24
  • 1970-01-01
相关资源
最近更新 更多