parse-platform - react native 并解析,登录和 cmd+R 后当前用户为空

标签 parse-platform reactjs react-native

我在使用 React Native 和 Parse JS SDK 时遇到问题。
我正在使用ParseReact

我已经构建了登录、注册和主视图,注册和登录效果很好,但是在我登录后 -> 定向到主视图,当我在模拟器中刷新应用程序(CMD+R)时,它让我再次回到登录 View ,我应该被带到主视图。

正如你所看到的,我已经为initialComponent设置了一个状态:

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

这允许我的导航器检查 currentUser 是否为空,然后加载 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 });

在我的 Xcode 控制台中,即使我之前已经登录过,每次刷新后我仍然会收到当前用户为空的信息。在我的解析应用程序上,我可以看到已创建新 session 。

在我的登录 View 中。

'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;

我的做法是错误的吗?友善的建议。或者解析本地存储/ session 有问题吗?

最佳答案

由于 React Native 仅提供异步存储,因此我们被迫将 Parse.User.current() 设为返回 Promise 的异步调用。由于您已经在使用 Parse+React,因此处理这个问题非常容易。根据用户是否登录而变化的组件 (MyApp) 应订阅 ParseReact.currentUser。这与当前用户保持同步,并允许您的组件在用户登录或注销时自动更新。有关此演示,请查看 AnyBudget demo在 GitHub 存储库中:

关于parse-platform - react native 并解析,登录和 cmd+R 后当前用户为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30498222/

相关文章:

javascript - 如何将 retire.js 用于 React 应用程序?

android - 未定义不是 TextInput onSubmitEditing Focus 的对象

reactjs - React Native map 自定义标记阻止标记 onPress

ios - 如何在 CFQuery TableViewController 中为 tableView 设置背景图片

android - Picasso 只在 BaseAdapter 中加载一张图像

parse-platform - CocoaPods 存储库上的 "PFFacebookUtils.framework"在哪里?

reactjs - 内联 fontFamily 无法在 React/Next.js 9 中工作

reactjs - 两个 svgo-loader 冲突

react-native - TouchableOpacity 中的 onPress 不会触发

ios - 如何在 TableViews 中使用 Parse 中的指针关系?