如何通过React Native中的组件共享登录状态

How to share login state through components in React Native?

本文关键字:组件 共享 登录 状态 何通过 React Native      更新时间:2024-02-10

在vue.js中,我使用$vm.$root.user存储用户数据并共享用户登录状态。在React.js中,有方便共享数据的上下文。

但我在React Native中没有找到任何关于它的文档,在React Nature中这样做的正确方法是什么?

我使用回流用于此目的(https://github.com/reflux/refluxjs)React&React Native。

它的工作方式是设置一个存储,其中包含您的登录状态、用户数据等。每当这些值发生变化时(通过ajax调用、用户操作等),您都可以从存储中激发一个以对象为参数的事件。(方法名称为"trigger")。

import Reflux from 'reflux'
import LoginActions from '../actions/LoginActions'
var LoginStore = Reflux.createStore({
isLoggedIn: false,
profile: {},
init: function() {
  // Do some initialization, e.g. checking if you've set some login information or tokens in local storage
},
listenables: [LoginActions],
loginUser: function(e) {
    // Do some call to a server to try and authenticate
    // fetch(...)
    if (fetch_result = true) {
        this.isLoggedIn = true;
        this.trigger({type: "LOGIN_STATUS", loggedIn: true});
    }
},
logoutUser: function(e) {
 // ...
}

上面提到的登录操作是一个非常简单的模块,例如:

import Reflux from 'reflux'
export default LoginActions = Reflux.createActions([
  'loginUser',
  'logoutUser',
 ]);

您的主应用程序应该通过添加侦听器来侦听存储事件,并且基于对象(您自己定义的),您可以更新状态或执行一些逻辑;例如

componentDidMount() {
    this.login = LoginStore.listen(this.loginStoreListener.bind(this));
 }
componenWillUnmount() {
    // Remove the listener on unmounting
    this.login();
}
loginStoreListener(obj) {
    switch (obj.type) {
      case "LOGIN_STATUS":
        this.setState({loggedIn: obj.loggedIn})
        break;
      case "PROFILE":
        this.setState({profile: obj.profile})
        break;
    }
}

在主应用程序中,根据loggedIn状态,您可以决定显示哪些视图,例如与Navigator结合显示。