How to split login state through components in React Native?

In vue.js, I use $vm.$root.userto store user data and share a username. React.js has a context for sharing data.

But I did not find a document about this in React Native, what is the right way to do this in React Native?

+4
source share
1 answer

I use Reflux for this purpose ( https://github.com/reflux/refluxjs ) in both React and React Native.

, , , .. , - ( ajax, ..), . ( - "" ).

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) {
 // ...
}

LoginActions , :

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.

+1

All Articles