本地和解析后,currentuser在登录后为空并且cmd + R.

Els*_*lsT 5 parse-platform reactjs react-native

我遇到了React Native和Parse JS SDK的问题.
我正在使用ParseReact

我已经建立了一个登录,注册和一个主视图,注册和登录工作正常,但我登录后 - >定向到主视图,当我在我的模拟器中刷新应用程序(CMD + R)时,它让我回来再次登录视图,我应该进入主视图.

如您所见,我为initialComponent设置了一个状态:

this.state = {        
      InitialComponent : ((!currentUser) ? LoginView : MainView)
};
Run Code Online (Sandbox Code Playgroud)

这允许我的导航器检查currentUser是否为null然后加载LoginView作为初始组件,否则设置主视图(用户登录)

'use strict';
var React = require('react-native');
var MainView = require('./MainView');
var LoginView = require('./LoginView');


var Parse = require('parse').Parse;
var ParseReact = require('parse-react');
Parse.initialize("mykey", "mykey");


var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
  Navigator,
  Component
} = React;


class MyApp extends Component {
    constructor(props) {
      super(props);

      var currentUser = Parse.User.current();
      console.log('Current User:' + currentUser);

      this.state = {        
        InitialComponent : ((!currentUser) ? LoginView : MainView)
      };
    }

   render() {
        return (
            <Navigator
              initialRoute={{
                 name : 'StatusList',
                 component: this.state.InitialComponent
              }}
              configureScene = {() =>{
                return Navigator.SceneConfigs.FloatFromRight;
              }}
              renderScene={(route, navigator) =>{
                if(route.component) {
                  return React.createElement(route.component, {navigator});
                }
              }}/>

        );
    }
}

AppRegistry.registerComponent('MyApp', function() { return MyApp });
Run Code Online (Sandbox Code Playgroud)

在我的Xcode控制台中,即使我之前已经登录,每次刷新后我仍然保持当前用户为空.在我的解析应用程序中,我可以看到已创建新会话.

在我的LoginView中.

'use strict';

var React = require('react-native');
var SignUp = require('./SignUp');
var MainView = require('./MainView');

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
  Navigator,
  AlertIOS,
  Component
} = React;

var styles = StyleSheet.create({
  container : {
      flex: 1,
      padding: 15,
      marginTop: 30,
      backgroundColor: '#0179D5',
   },
  text: {
    color: '#000000',
    fontSize: 30,
    margin: 100
  },

  headingText: {
    color: '#fff',
    fontSize: 40,
    fontWeight: '100',
    alignSelf: 'center',
    marginBottom: 20,
    letterSpacing: 3
  },

  textBox: {
    color: 'white',
    backgroundColor: '#4BB0FC',
    borderRadius: 5,
    borderColor: 'transparent',
    padding:10,
    height:40,
    borderWidth: 1,
    marginBottom: 15,
  },

  greenBtn: {
    height: 36,
    padding: 10,
    borderRadius: 5,
    backgroundColor: '#2EA927',
    justifyContent: 'center'
  },

  signUpButton: {
    marginTop: 10,
    height: 36,
    padding: 10,
    borderRadius: 5,
    backgroundColor: '#FF5500',
    justifyContent: 'center'

  },

  btnText: {
    color : '#fff',
    fontSize: 15,
    alignSelf: 'center'
  },

  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },

   loginForm : {
      flex:1,
      marginTop:100
   }
});

class LoginView extends Component {

    constructor(props) {
      super(props);
      this.state = {
        username: '',
        password: ''
      };

    }

    checkLogin() {
        var success = true;
        var state = this.state;
        for(var key in state){
          if(state[key].length <= 0){
            success = false;
          }
        }

        if(success) {
          this._doLogin();
        } else {
          //show alert
          AlertIOS.alert('Error','Please complete all fields',
            [{text: 'Okay', onPress: () => console.log('')}]
          );
        }
    }

    goMainView() {
      this.props.navigator.push({
        title: "Home",
        component: MainView
      });
    }

    goSignUp() {
      this.props.navigator.push({
        title: "Sign Up",
        component: SignUp
      });
    }

    _doLogin() {
      var parent = this;
      Parse.User.logIn(this.state.username, this.state.password, {
        success: function(user) {
            parent.goMainView();
        },
        error: function(user, error) {
          AlertIOS.alert('Login Error', error.message,
            [{text: 'Okay', onPress: () => console.log('')}]
          );
        }
      });
    }

    onUsernameChanged(event) {
      this.setState({ username : event.nativeEvent.text });
    }

    onPasswordChanged(event) {
      this.setState({ password : event.nativeEvent.text });
    }

    render() {
       return(
          <View style={styles.container}>
            <View style={styles.loginForm}>
                <Text style={styles.headingText}>
                  MyStatus
                </Text>

               <TextInput style={styles.textBox}
                placeholder='Username'
                onChange={this.onUsernameChanged.bind(this)}
                placeholderTextColor='#fff'
                autoCorrect={false}
               >
               </TextInput>

               <TextInput style={styles.textBox}
                placeholder='Password'
                onChange={this.onPasswordChanged.bind(this)}
                placeholderTextColor='#fff'
                password={true}
               >
               </TextInput>

               <TouchableHighlight style={styles.greenBtn}
                  underlayColor='#33B02C'
                  onPress={this.checkLogin.bind(this)}>
                    <Text style={styles.btnText}>Login</Text>

                </TouchableHighlight>


                <TouchableHighlight style={styles.signUpButton}
                  underlayColor='#D54700'
                  onPress={this.goSignUp.bind(this)}>
                    <Text style={styles.btnText}>Sign Up</Text>

                </TouchableHighlight>
            </View>

          </View>
        );
    }
}

module.exports = LoginView;
Run Code Online (Sandbox Code Playgroud)

我这样做是错误的吗?好心劝告.或者解析localstorage/session是否有问题?

And*_*w I 6

因为React Native只提供异步存储,所以我们不得不进行Parse.User.current()一次返回Promise的异步调用.既然你已经在使用Parse+React,那么处理这个问题真的很容易.根据用户是否登录(MyApp)而更改的组件应订阅ParseReact.currentUser.它与当前用户保持同步,并允许您的组件在用户登录或注销时自动更新.有关此演示,请查看GitHub存储库中的AnyBudget 演示:


小智 5

在本机反应...

import Parse from 'parse/react-native';

Parse.User.currentAsync()
.then((currentUser)=>{
    if (currentUser) {
        Alert.alert('', JSON.stringify(currentUser))
    }
});
Run Code Online (Sandbox Code Playgroud)