首页 文章

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

提问于
浏览
1

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

在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保存访问令牌是一个好习惯吗?

如果没有,我该怎么用?

1 回答

  • 2

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

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

    • 调用redux' createStore 时从localStorage读取访问令牌并将其传递到预加载状态 . 要么..

    • 发送类似 SET_ACCESS_TOKEN 的操作,以便稍后将令牌添加到redux存储 .

    • 要在成功登录后立即保存令牌,您可以在相应的异步操作创建器中触发副作用(调用负责向localStorage写入内容的模块) .

    就是这样,不需要额外的模块 .

相关问题