使用redux在react-native应用程序中保存访问令牌的最佳做法是什么?

时间:2017-08-05 06:56:23

标签: firebase react-native redux

使用redux在react-native app中保存访问令牌的最佳做法是什么?

在Redux中,我曾经保存整个凭据,包括一些用户信息到状态:

//Actions
export const successfulLogin = (firebaseAuth) => ({
    type: 'LOGIN_SUCCESSFUL',
    firebaseAuth
});

//Reducer
const authentication = (state = {}, action) => {
    switch (action.type) {
        case 'LOGIN_SUCCESSFUL':
            return {
                ...state,
                firebaseAuth: action.firebaseAuth
            };
        default:
            return state;
    }
}
export default authentication

之后,我找到了一个新模块redux-persist,它可以帮助我将状态保存到设备存储localStorage。但是,商店中的所有内容都将被保存。使用redux-persist保存访问令牌是一个好习惯吗?

如果没有,我该怎么用?

2 个答案:

答案 0 :(得分:2)

我认为您所描述的内容有效,但如果您只需要一个访问令牌,则保存整个商店有点过分。因此,我说最好的做法就是通过一些代码来完成你所需要的。

作为使用redux-persist的替代方法,您可以自己执行此副作用处理:

  1. 当redux'时,从localStorage读取访问令牌。调用createStore并将其传递到预加载状态。或..
  2. 发送SET_ACCESS_TOKEN之类的操作,以便稍后将该令牌添加到redux商店。
  3. 要在成功登录后立即保存令牌,您可以在相应的异步操作创建器中触发副作用(调用负责向localStorage写入内容的模块)。
  4. 那就是它,不需要额外的模块。

答案 1 :(得分:0)

问这个问题已经有一段时间了,但是使用redux-persist,您不需要保存整个商店。您可以提供要存储的密钥,它将忽略未指定的密钥。

相关问题