反应问题

时间:2017-08-03 13:32:42

标签: api react-native login

我有一个非常简单的登录屏幕,用户输入用户名和密码。当用户点击登录按钮时,如果输入的用户ID /密码组合正确,则流程将移至下一个屏幕。

点击登录按钮,我用一个用户ID和密码作为输入来调用API。 API以JSON格式返回来自DB的匹配记录计数。如果计数> 0,则登录成功。

问题:我必须单击两次登录按钮。当我点击登录按钮时没有任何反应,但如果我再次点击它然后我收到失败消息或移动到第二个屏幕取决于用户ID /密码组合。我正在复制下面的代码。我会感激任何帮助。

import React, { Component } from 'react';
import {
  AppRegistry,
  View,
  Image,
  StyleSheet,
  KeyboardAvoidingView,
  TextInput,
  TouchableOpacity,
  Text,
  StatusBar,
  Alert
} from 'react-native';

import {
  StackNavigator 
} from 'react-navigation';

export default class Login extends Component {

  constructor(props) {
    super(props)

    this.state = {
      email: '',
      password: '',
      uCount: -1,
      data: []
    };
  }

   getData(){
    var url="https://myurl/verifySubscription.php?email=" + this.state.email + "&password=" + this.state.password;
    console.log("URL:", url);
    return fetch(url)
    .then((response) => response.json())
    .then((responseJson) => {
     this.setState({
      uCount: responseJson.count
    })
    })
    .catch((error) => {
      console.error(error);
    });
  }

async _onPressButton() {

      await this.getData();
        console.log("uCount:", this.state.uCount);
        if (this.state.uCount < 1) {
            Alert.alert('Login Failed: Incorrect email or password')
        } else {
            this.props.navigation.navigate('LoginSuccess', { email: this.state.email, password: this.state.password})      
        }
  }

  render() {

    return (
      <KeyboardAvoidingView behavior="padding" style={styles.wrapper}>
          <View style={styles.topView}>
             <Image style={styles.imageStyle}
             source={require('../images/main.jpg')}
             />
          </View>         
          <View style={styles.bottomView}>
              <StatusBar
                 barStyle="light-content"
              />
              <TextInput style={styles.Input}
                placeholder="Email"
                placeholderTextColor="rgba(255,255,255,0.7)"
                keyBoardType='email-address'
                returnKeyType="next"
                autoCapitalize="none"
                autoCorrect={false}
                onSubmitEditing={() => this.passwordInput.focus()}
                onChangeText={(text) => this.setState({email:text})}
              />
              <TextInput style={styles.Input}
                placeholder="Password"
                placeholderTextColor="rgba(255,255,255,0.7)"
                returnKeyType="go"
                secureTextEntry
                autoCapitalize="none"
                autoCorrect={false}
                ref={(next) => this.passwordInput = next}
                onChangeText={(text) => this.setState({password:text})}
              />
              <TouchableOpacity style={styles.button1Container} onPress={ this._onPressButton.bind(this) }>
                <Text style={styles.buttonText}>
                  Login
                </Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.button2Container}>
                <Text style={styles.buttonText}>
                  Sign up
                </Text>
              </TouchableOpacity>
          </View>
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({
    wrapper: {
       backgroundColor: '#4A7AA5',
       flex: 1
    },
    topView: {
        flexGrow: 1
    },
    imageStyle: {
        width: null,
        flex: 1
    },
    bottomView: {
      padding: 20
    },
    Input: {
      height:40,
      backgroundColor: 'rgba(255,255,255,0.3)',
      marginBottom: 10,
      color: '#FFF',
      paddingHorizontal: 10
    },
    button1Container: {
      backgroundColor: 'rgba(200,200,255,0.3)',
      padding: 10
    },
    buttonText: {
      textAlign: 'center',
      color: '#FFF',
      fontWeight: '700'
    },
    button2Container: {
      padding: 10
    }
});

1 个答案:

答案 0 :(得分:0)

当您按下按钮时,问题可能与异步过程有关。 fetch将返回一个promise,然后在响应完成后可以解析。试试这个,不要使用等待(es2017),只需要es6。

getData(){
    var url="https://myurl/verifySubscription.php?email=" + this.state.email + 
   "&password=" + this.state.password;
    console.log("URL:", url);
    return fetch(url);
}

_onPressButton() {
    this.getData().then((response) => response.json())
            .then((responseJson) => {
       const cnt = responseJson.cnt;

      if (cnt < 1) {
        Alert.alert('Login Failed: Incorrect email or password')
      } else {
        this.props.navigation.navigate('LoginSuccess', { email: 
          this.state.email, password: this.state.password})      
      }
   });
}