React native 单击“登录”按钮不工作时显示加载动画

React native 单击“登录”按钮不工作时显示加载动画,react-native,React Native,我有以下代码。我有两个问题。第一个,当我点击登录按钮时,显示加载动画。但是,它应该切换登录过程是成功还是失败。它不起作用了。第二,如果我没有添加这行代码“this.toggleLoader=this.toggleLoader.bind(this);”,则toggleLoader函数会显示错误,this.setState不是一个函数。请注意,成功登录后,页面将导航到新屏幕主页。在此之前如何切换加载程序?如果在If循环后调用函数toggleLoader(),则不起作用 import React, {

我有以下代码。我有两个问题。第一个,当我点击登录按钮时,显示加载动画。但是,它应该切换登录过程是成功还是失败。它不起作用了。第二,如果我没有添加这行代码“this.toggleLoader=this.toggleLoader.bind(this);”,则toggleLoader函数会显示错误,this.setState不是一个函数。请注意,成功登录后,页面将导航到新屏幕主页。在此之前如何切换加载程序?如果在If循环后调用函数toggleLoader(),则不起作用

import React, {Component} from 'react'
import {
Alert,
AsyncStorage,
Keyboard,
Text,
View,
TextInput,
TouchableHighlight, TouchableOpacity,
Image,
ActivityIndicator,
} from 'react-native'
import config from "../../../../config";
import styles from './style'
import {Icon} from "react-native-elements";

class Login extends Component {

constructor(props) {
    super(props);
    this.state = {
        credentials: {
            email: "",
            password: "",
        },
        loading: false,
    };
    this.toggleLoader = this.toggleLoader.bind(this);
}

updateText(text, field) {
    let newCredentials = Object.assign(this.state.credentials);
    newCredentials[field] = text;
    this.setState = ({
        credentials: newCredentials
    })
}

toggleLoader() {
    this.setState({
        loading: !this.state.loading
    });
}

async login() {
    Keyboard.dismiss();
    let credentials = this.state.credentials;
    if (this.state.credentials.email == '' || this.state.credentials.password == '') {
        Alert.alert("Please fill all the fields.");
    } else {

            const that = this;
            credentials.email = that.state.credentials.email.toLowerCase();
            // start loading when all fields are fill
             this.setState({ loading: !this.state.loading });

            fetch(config.baseURL + 'mobileapi/get_token/?username=' + `${that.state.credentials.email}` + '&password=' + `${that.state.credentials.password}`, {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    credentials: credentials,
                }),
            })
                .then((response) => response.json())
                .then(responseJson => {
                    //stop loading after successful response
                    this.setState({ loading: !this.state.loading });

                    if (responseJson.confirmation === "success") {
                       // alert(JSON.stringify(responseJson.data));
                        AsyncStorage.setItem('USER_ID', responseJson.data.user_id);
                        AsyncStorage.setItem('USER_NAME', responseJson.data.user_name);
                        AsyncStorage.setItem('USER_TYPE', responseJson.data.user_type);
                        AsyncStorage.setItem('FIRST_NAME', responseJson.data.first_name);
                        AsyncStorage.setItem('LAST_NAME', responseJson.data.last_name);
                        AsyncStorage.setItem('EMAIL', responseJson.data.user_email);
                        AsyncStorage.setItem('AUTHENTICATION_TOKEN', responseJson.data.token);

                        setTimeout(() => {
                            this.props.navigation.navigate("Home")
                        }, 500);

                    } else {


                        setTimeout(() => {
                            //code to handle an error
                            throw new Error(responseJson.message);
                        }, 500);

                    }
                })
                .catch((err) => {

                    //stop loading
                    this.setState({ loading: !this.state.loading });

                    setTimeout(() => {
                        if (JSON.stringify(err.message) === JSON.stringify('Network request failed')) {
                            alert('Please check your internet connection or try again later');
                        } else {
                            alert(JSON.stringify(err.message));
                        }
                    }, 500);

                })

    }
}

render() {
    const loginText = (this.state.loader) ? 'Loading' : 'Login';
    return (
        <View style={styles.container}>
            <Image source={require('../../../../assets/images/icons/logo.png')}
                   style={{width: 99, height: 99, margin: 5,}}/>
            <Text style={{fontSize: 20, margin: 20, color: "#0aa1e2"}}>Test App</Text>
            <View style={styles.inputContainer}>
                <Image style={styles.inputIcon}
                       source={require('../../../../assets/images/icons/username.png')}/>
                <TextInput style={styles.inputs}
                           placeholder="Username"
                           keyboardType="email-address"
                           underlineColorAndroid='transparent'
                           onChangeText={text => {
                               this.updateText(text, 'email')
                           }} value={this.state.email}
                           autoCorrect={false}
                           autoCapitalize={"none"}
                />
            </View>
            <View style={styles.inputContainer}>
                <Image style={styles.inputIcon}
                       source={require('../../../../assets/images/icons/password.png')}/>
                <TextInput style={styles.inputs}
                           placeholder="Password"
                           secureTextEntry={true}
                           underlineColorAndroid='transparent'
                           onChangeText={text => {
                               this.updateText(text, 'password')
                           }}
                           value={this.state.password}
                           autoCorrect={false}
                           secureTextEntry/>
            </View>
            <TouchableHighlight style={[styles.buttonContainer, styles.loginButton]}
                                onPress={this.login.bind(this)} >
                <View style={{justifyContent: 'center', flex: 1, flexDirection: 'row'}}>
                    {this.state.loading === false ?
                        <Icon name='login' type='entypo' size={16} color='white'/> :
                        <ActivityIndicator size="small" color="#ffffff"/>}
                    <Text style={styles.loginText}> {loginText} </Text>
                </View>
            </TouchableHighlight>
        </View>
    );
}
}

export default Login;
import React,{Component}来自“React”
进口{
警觉的,
异步存储,
键盘
文本,
看法
文本输入,
可触摸高光,可触摸不透明度,
形象,,
活动指示器,
}从“反应本机”
从“../../../../config”导入配置;
从“./style”导入样式
从“react native elements”导入{Icon};
类登录扩展组件{
建造师(道具){
超级(道具);
此.state={
证书:{
电邮:“,
密码:“”,
},
加载:false,
};
this.toggleLoader=this.toggleLoader.bind(this);
}
updateText(文本,字段){
让newCredentials=Object.assign(this.state.credentials);
newCredentials[字段]=文本;
this.setState=({
凭据:新凭据
})
}
toggleLoader(){
这是我的国家({
正在加载:!this.state.loading
});
}
异步登录(){
键盘;
让凭据=this.state.credentials;
if(this.state.credentials.email=''| | this.state.credentials.password=''){
Alert.Alert(“请填写所有字段”);
}否则{
常数=this;
credentials.email=that.state.credentials.email.toLowerCase();
//当所有字段都已填充时开始加载
this.setState({loading:!this.state.loading});
fetch(config.baseURL++'mobileapi/get_-token/?username='++`${that.state.credentials.email}`+'&password='++`${that.state.credentials.password}`{
方法:“POST”,
标题:{
接受:'application/json',
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify({
全权证书:全权证书,
}),
})
.then((response)=>response.json())
.然后(responseJson=>{
//成功响应后停止加载
this.setState({loading:!this.state.loading});
如果(responseJson.confirmation==“成功”){
//警报(JSON.stringify(responseJson.data));
AsyncStorage.setItem('USER\u ID',responseJson.data.USER\u ID);
AsyncStorage.setItem('USER\u NAME',responseJson.data.USER\u NAME);
AsyncStorage.setItem('USER\u TYPE',responseJson.data.USER\u TYPE);
AsyncStorage.setItem('FIRST\u NAME',responseJson.data.FIRST\u NAME);
AsyncStorage.setItem('LAST_NAME',responseJson.data.LAST_NAME);
AsyncStorage.setItem('EMAIL',responseJson.data.user\u EMAIL);
AsyncStorage.setItem('AUTHENTICATION_TOKEN',responseJson.data.TOKEN);
设置超时(()=>{
this.props.navigation.navigate(“主页”)
}, 500);
}否则{
设置超时(()=>{
//处理错误的代码
抛出新错误(responseJson.message);
}, 500);
}
})
.catch((错误)=>{
//停止加载
this.setState({loading:!this.state.loading});
设置超时(()=>{
if(JSON.stringify(err.message)==JSON.stringify('networkrequest failed')){
警报(“请检查您的internet连接或稍后再试”);
}否则{
警报(JSON.stringify(err.message));
}
}, 500);
})
}
}
render(){
const loginText=(this.state.loader)?'Loading':'Login';
返回(
测试应用程序
{
this.updateText(文本“email”)
}}值={this.state.email}
自动更正={false}
自动资本化={“无”}
/>
{
this.updateText(文本“密码”)
}}
值={this.state.password}
自动更正={false}
secureTextEntry/>
{this.state.loading==false?
:
}
{loginText}
);
}
}
导出默认登录;
我已经更新了您的login()方法。请试一试。这可能对你有帮助

 async login() {
        Keyboard.dismiss();
        let credentials = this.state.credentials;
        if (this.state.credentials.email == '' || this.state.credentials.password == '') {
            Alert.alert("Please fill all the fields.");
        } else {
            credentials.email = that.state.credentials.email.toLowerCase();
            // start loading when all fields are fill
            this.toggleLoader();
            fetch(config.baseURL + 'mobileapi/get_token/?username=' + `${that.state.credentials.email}` + '&password=' + `${that.state.credentials.password}`, {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    credentials: credentials,
                }),
            })
                .then((response) => response.json())
                .then(responseJson => {
                      //stop loading after successful response
                        this.toggleLoader();
                    if (responseJson.confirmation === "success") {
                        AsyncStorage.setItem('USER_ID', responseJson.data.user_id);
                        AsyncStorage.setItem('USER_NAME', responseJson.data.user_name);
                        AsyncStorage.setItem('USER_TYPE', responseJson.data.user_email);
                        AsyncStorage.setItem('AUTHENTICATION_TOKEN', responseJson.data.token);
                        setTimeout(() => {
                            this.props.navigation.navigate("Home")
                        }, 500);
                    } else {
                        setTimeout(() => {
                            //code to handle an error
                        }, 500);
                    }
                })
                .catch((err) => {
                    //stop loading
                    this.toggleLoader();
                    setTimeout(() => {
                        if (JSON.stringify(err.message) === JSON.stringify('Network request failed')) {
                            alert('Please check your internet connection or try again later');
                        } else {
                            alert(JSON.stringify(err.message));
                        }
                    }, 500);
                })
        }
    }
您已在文本输入中设置电子邮件,如this.state.email。这应该是this.state.credentials.email。密码也必须遵循同样的规则。更改render()方法的onPress事件如下:

   render() {
    const loginText = (this.state.loader) ? 'Loading' : 'Login';
    return (
        <View style={styles.container}>
            <Image source={require('../../../../assets/images/icons/logo.png')}
                   style={{width: 99, height: 99, margin: 5,}}/>
            <Text style={{fontSize: 20, margin: 20, color: "#0aa1e2"}}>Test App</Text>
            <View style={styles.inputContainer}>
                <Image style={styles.inputIcon}
                       source={require('../../../../assets/images/icons/username.png')}/>
                <TextInput style={styles.inputs}
                           placeholder="Username"
                           keyboardType="email-address"
                           underlineColorAndroid='transparent'
                           onChangeText={text => {
                               this.updateText(text, 'email')
                           }} 
                           value={this.state.credentials.email}
                           autoCorrect={false}
                           autoCapitalize={"none"}
                />
            </View>
            <View style={styles.inputContainer}>
                <Image style={styles.inputIcon}
                       source={require('../../../../assets/images/icons/password.png')}/>
                <TextInput style={styles.inputs}
                           placeholder="Password"
                           secureTextEntry={true}
                           underlineColorAndroid='transparent'
                           onChangeText={text => {
                               this.updateText(text, 'password')
                           }}
                           value={this.state.credentials.password}
                           autoCorrect={false}
                           secureTextEntry/>
            </View>
            <TouchableHighlight style={[styles.buttonContainer, styles.loginButton]}
                                onPress={this.login.bind(this)} >
                <View style={{justifyContent: 'center', flex: 1, flexDirection: 'row'}}>
                    {this.state.loading === false ?
                        <Icon name='login' type='entypo' size={16} color='white'/> :
                        <ActivityIndicator size="small" color="#ffffff"/>}
                    <Text style={styles.loginText}> {loginText} </Text>
                </View>
            </TouchableHighlight>
        </View>
    );
}

嗨,我试过上面的代码。它显示错误:“TypeError:this.setState不是函数”。我认为它在函数toggleLoader()中显示了这个错误。我不知道为什么。好的,将这个.toggleLoader()替换为这个.setState({loading:!this.state.loading});在所有地方检查它是否工作?让我知道结果
updateText(text, field) {
    let newCredentials = Object.assign(this.state.credentials);
    newCredentials[field] = text;
    // setState should be done like this
    this.setState({
        credentials: newCredentials
    })
}