【问题标题】:Break command is not working in if condition of for loop in React Native如果在 React Native 中的 for 循环条件下,Break 命令不起作用
【发布时间】:2021-07-11 20:18:46
【问题描述】:

我正在尝试通过从 firebase 实时数据库中获取数据来登录用户,但是我的 break 命令无法正常工作,因为一旦输入的用户名和密码匹配,它仍然会通过登录到显示密码或用户名不正确的警报消息用户帐户,并且它不会为第一个值显示此警报,而是显示剩余值。我需要帮助!

import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
  Alert,
  ActivityIndicator,
} from "react-native";
import firebase from "../../database/firebase";
import CustomHeader from "../CustomHeader";
import { ImageBackground } from "react-native";

var categories = [];
var categories1 = [];
var categories2 = [];
var data;
// var key;
// var data;
var count = 0;
export default class SignIn extends Component {
  constructor() {
    super();
    this.state = {
      email: "",
      password: "",
      isLoading: false,
      menu1:[],
      menu2: [],
    };
  }

  updateInputVal = (val, prop) => {
    const state = this.state;
    state[prop] = val.trim();
    this.setState(state);
  };

  userLogin = () => {
    console.log(this.state.email);
    console.log(this.state.password);


    firebase.database().ref('users/uid/').once('value').then(function(snapshot) {

      console.log("        Again");


      snapshot.forEach(function(snap) {
         const item = snap.val();
         categories1.push(item);

         const item1 = snap.key;
         categories2.push(item1);
          
          count++;
             
      });
      console.log(count);

      /// For object Values
      console.log("Values");
      this.setState( {    //PASSING VARIABLE TO STATE
        menu1 :categories1
    })
    console.log(this.state.menu1);

     /// For object Names
     console.log("Names");
      this.setState( {    //PASSING VARIABLE TO STATE
        menu2 :categories2
    })
    console.log(this.state.menu2);



  /// Use this method to login user ///
 /// With State Array ///
 
//  const name = "AlFateh";
//   for(let i =0 ; i< count; i++)
//   {
//     if(this.state.menu2[i] == name)
//     {
//       console.log(name);
//     }
//     // console.log('nothing');
//   }



   
    
      
     


    if (this.state.email === "" || this.state.password === "") {
      Alert.alert("Enter details to signin!");
    } else {

      this.setState({
        isLoading: true,
      });


      for(let i =0 ; i< count; i++)
      {
        if( this.state.password === this.state.menu1[i] && this.state.menu2[i] === this.state.email)
        {
          console.log("User logged-in successfully!");
          this.setState({
            isLoading: false,
            email: "",
            password: "",
          });
          
          this.props.navigation.navigate("HomeApp");
          break;
          
        }
        if( this.state.menu1[i] !== this.state.password || this.state.menu2[i] !== this.state.email)
        {
          Alert.alert("Incorrect Email Or Password!")        
        this.setState({
          isLoading: false,

          
         });
         
      
        }                              
             
      }
      
        
    }
  }.bind(this));
    this.empty();
  };

  empty()
      {
        categories1 = [];
        categories2 = [];
        count = 0;

      }
      

  render() {
    if (this.state.isLoading) {
      return (
        <ImageBackground
          source={require("../../assets/yellow_bus.jpg")}
          style={{ width: "100%", height: "100%" }}
        >
          <View style={styles.preloader}>
            <ActivityIndicator size="large" color="#9E9E9E" />
          </View>
        </ImageBackground>
      );
    }
    return (
      <ImageBackground
        source={require("../../assets/yellow_bus.jpg")}
        style={{ width: "100%", height: "100%" }}
      >
        <View style={{ flex: 1, position: "absolute", width: 370, top: 1 }}>
          <CustomHeader title="Sign In" navigation={this.props.navigation} />
        </View>

        <View style={styles.container}>
          <TextInput
            style={styles.inputStyle}
            placeholder="Email"
            placeholderTextColor="snow"
            value={this.state.email}
            onChangeText={(val) => this.updateInputVal(val, "email")}
          />
          <TextInput
            style={styles.inputStyle}
            placeholder="Password"
            placeholderTextColor="snow"
            value={this.state.password}
            onChangeText={(val) => this.updateInputVal(val, "password")}
            maxLength={15}
            secureTextEntry={true}
          />

          <TouchableHighlight
            style={{
              elevation: 8,
              backgroundColor: "sandybrown",
              borderRadius: 1010,
              paddingVertical: 10,
              paddingHorizontal: 1,
            }}
            onPress={() => this.userLogin()}
          >
            <Text style={styles.appButtonText}>Sign in</Text>
          </TouchableHighlight>

          <Text
            style={styles.loginText}
            onPress={() => this.props.navigation.navigate("Register")}
          >
            Don't have account? Click here to signup
          </Text>
        </View>
      </ImageBackground>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    padding: 35,
    paddingTop: 155,
  },
  inputStyle: {
    width: "90%",
    marginBottom: 15,
    paddingBottom: 15,
    alignSelf: "center",
    borderColor: "whitesmoke",
    fontSize: 20,
    borderRadius: 20,
    paddingVertical: 15,
    color: "snow",
    backgroundColor: "sandybrown",
  },
  loginText: {
    color: "whitesmoke",
    marginTop: 25,
    textAlign: "center",
  },
  preloader: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    position: "absolute",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#fff",
  },
  appButtonText: {
    fontSize: 18,
    color: "#fff",
    fontWeight: "bold",
    alignSelf: "center",
    textTransform: "uppercase",
  },
});

【问题讨论】:

    标签: firebase react-native firebase-realtime-database react-hooks break


    【解决方案1】:

    看起来您有多个this.state.menu1this.state.menu2,它们是否包含不同的emailpassword 或者可能是空的?如果是,那么您的 for 循环逻辑不正确。请尝试以下操作:

    let loggedIn = false;
    for(let i =0 ; i< count; i++)
    {
        if( this.state.password === this.state.menu1[i] && this.state.menu2[i] === this.state.email)
        {
          console.log("User logged-in successfully!");
          loggedIn = true;
          this.setState({
            isLoading: false,
            email: "",
            password: "",
          });
          
          this.props.navigation.navigate("HomeApp");
          break;
          
        }             
    }
    
    if(!loggedIn)
    {
        Alert.alert("Incorrect Email Or Password!")        
        this.setState({
          isLoading: false,      
         });      
    }                              
    

    注意if(!loggedIn) 语句在for 循环之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多