【问题标题】:How to manage user session in React Native?如何在 React Native 中管理用户会话?
【发布时间】:2019-09-03 18:15:30
【问题描述】:

我正在学习 React Native 以及用 TypeScript 编写的 React Navigation 和 GraphQL。我将使用 Facebook 登录让用户注册(使用 Passport.js 或 Auth0)

如何在 React Native 中管理用户会话?我需要使用 Redux 吗?

请赐教。

【问题讨论】:

  • 对此有很大的了解请visit

标签: javascript typescript react-native


【解决方案1】:

由于会话通常包含敏感信息,我建议避免使用AsyncStorage 或类似的解决方案。

react-native-keychain 使用更安全的方法。它将会话存储在安全存储中。

示例代码

import * as Keychain from 'react-native-keychain';

// When you want to store the session
const rawValue = JSON.stringify(session);
await Keychain.setGenericPassword('session', rawValue);

// When you want to retrieve the session
const credential = await Keychain.getGenericPassword();
const session = JSON.parse(credential.password)

【讨论】:

  • 因为 AsyncStortage 已从核心 React-Native 中删除。这种方法在涉及安全的应用程序中会更好。
  • 你也推荐给JWT吗?
  • @Rario 是的,我用上述方法存储了我的 JWT 令牌。
【解决方案2】:

您可以使用 AsyncStorage 保存用户会话(数据)。请按照 React Native Website 的推荐尝试这个库 async-storage

存储数据

storeData = async () => {
  try {
    await AsyncStorage.setItem('@storage_Key', 'stored value')
  } catch (e) {
    // saving error
  }
}

读取数据

getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

【讨论】:

  • React Native 新手,如何在 React Native 项目中导入或添加库依赖
【解决方案3】:

您可以在 redux 中添加用户会话并使用 redux-persist 持久化您的 redux 数据。

所以每次调用远程端点时都将用户会话信息添加到 api 调用标头

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-20
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2021-10-02
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多