简体   繁体   English

如何在 React Native 中管理用户会话?

[英]How to manage user session in React Native?

I'm learning React Native with React Navigation and GraphQL written in TypeScript.我正在学习 React Native 和用 TypeScript 编写的 React Navigation 和 GraphQL。 I will use Facebook Login for users to register (with Passport.js or Auth0)我将使用 Facebook 登录让用户注册(使用 Passport.js 或 Auth0)

How do I manage user session in React Native?如何在 React Native 中管理用户会话? Do I need to use Redux?我需要使用 Redux 吗?

Please enlighten me.请赐教。

Because session usually contains sensitive info, I would advise avoiding using AsyncStorage or similar solution.因为会话通常包含敏感信息,我建议避免使用AsyncStorage或类似的解决方案。

Use more secure approach with react-native-keychain .使用更安全的方法react-native-keychain It will store the session on secure storage.它将会话存储在安全存储中。

Sample Code示例代码

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)

You can save user session(data) using AsyncStorage .您可以使用 AsyncStorage 保存用户会话(数据)。 Please try this library async-storage as recommended By React Native Website请按照 React Native网站的推荐尝试这个库async-storage

Store data存储数据

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

Read data读取数据

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

you can add user session in redux and persist your redux data with redux-persist.您可以在 redux 中添加用户会话并使用 redux-persist 保存您的 redux 数据。

so add user session info to api call header each time when you call remote endpoint因此,每次调用远程端点时,将用户会话信息添加到 api 调用标头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM