Проблема аутентификации при входе в React Native - PullRequest
0 голосов
/ 21 июня 2020

У меня проблема со страницей аутентификации при входе. Приложение не позволяет мне вводить имя пользователя. Вместо этого он генерирует запрос «Введите имя пользователя и пароль»: image

***LoginScreen.js***

import React from 'react'
import{View,Text,StyleSheet,TextInput,TouchableOpacity}from 'react-native'
import axios from 'axios'
import AsyncStorage from '@react-native-community/async-storage'

class LoginScreen extends React.Component{

    state={
      username:"",
      password:"",
      loading:false
    }
     onChangeHandle(state,value){
       this.setState({
           [state]:value
       })
     }
     dologin(){
     const{username,password}=this.state
     if(username && password){
        const req={
            "email":username,
            "password":password
        }
        this.setState({
            loading:true
        })
        axios.post("https://reqres.in/api/login",req)
        .then(
            res=>{
               this.setState({
                   loading:false,
               })
               AsyncStorage.setItem("token",res.data.token)
               .then(
                   res=>{
                    this.props.navigation.navigate("App")
                    alert("Login Successful")
                   }
               )
               
            },
            err=>{
                this.setState({
                    loading:false
                })
                alert("User Name Password is wrong")
            }
        )
        }
     
     else{
         alert("Enter Username and password")
     }
    }
     
    render(){
        const{username,password,loading}=this.state
        return(
            <View
            style={styles.container}
            >
                <View
                style={styles.formWrapper}
                >
                    <Text
                    style={styles.welcomeText}
                    >Welcome Back User            
                    </Text>
                    <View
                    style={styles.formRow}
                    >
                    <TextInput
                    style={styles.textInput}
                       placeholder="Enter username"
                       placeholderTextColor="#333"
                       value={username}
                       onChangeText={(value)=>this.dologin()}
                       disabled={loading}
                      />
                      </View>
                      <View
                      style={styles.formRow}
                      >
                      <TextInput
                      style={styles.textInput}
                       placeholder="Enter password"
                       placeholderTextColor="#333"
                       secureTextEntry={true}
                       value={password}
                       onChangeText={(value)=>this.dologin('password',value)}
                      />
                    </View>
                    <TouchableOpacity
                    activeOpacity={0.8}
                    style={{
                        ...styles.signinBtn,
                        backgroundColor:loading ? "#ddd" :"blue"
                    }}
                    onPress={()=>this.dologin()}
                    disabled={loading}
                    >
                    <Text
                    style={styles.signinText}
                        >
                            {loading ? "Loading...":"SignIn"}
                        </Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }
}
export default LoginScreen;

const styles=StyleSheet.create({
    container:{
        height:'100%',
        alignItems:'center',
        justifyContent:"center"
    },
    formWrapper:{
        width:'80%',
        marginBottom:10
    },
    formRow:{ 
    marginBottom:10
    },
    textInput:{
     backgroundColor:'#ddd',
     height:40,
     paddingHorizontal:10,
     color:'#333'
    },
   welcomeText:{
       textAlign:'center',
       marginBottom:30,
       fontSize:24,
       fontWeight:"bold"
   },
   signinBtn:{
    paddingVertical:10
   },
   signinText:{
   textAlign:"center",
   color:'#fff',
   fontSize:18,
   fontWeight:"bold"

   }
})

Кажется, я не могу найти причину root ошибки. Я читал код для отладки много раз. Прошло уже несколько часов, и это на самом деле довольно неприятно.

1 Ответ

2 голосов
/ 21 июня 2020

Вы вызываете метод, выполняйте вход в систему всякий раз, когда изменяется значение входного значения, вам нужно вызвать этот метод только один раз при нажатии на кнопку, а для получения значений из поля ввода вам необходимо использовать присоединение метода this.setState и пример кода, который вам поможет.

  <TextInput
                    style={styles.textInput}
                       placeholder="Enter username"
                       placeholderTextColor="#333"
                       value={username}
                       **`onChangeText={value=>this.setState({username:value })}`**
                       disabled={loading}
                      />
                      </View>
                      <View
                      style={styles.formRow}
                      >
                      <TextInput
                      style={styles.textInput}
                       placeholder="Enter password"
                       placeholderTextColor="#333"
                       secureTextEntry={true}
                       value={password}
                       **onChangeText={value=>this.setState({password:value})}**
                      />
                    </View>
                    <TouchableOpacity
                    activeOpacity={0.8}
                    style={{
                        ...styles.signinBtn,
                        backgroundColor:loading ? "#ddd" :"blue"
                    }}
                    onPress={()=>this.dologin()}
                    disabled={loading}
                    >
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...