单击登录按钮不起作用时显示加载动画

时间:2019-02-01 05:26:23

标签: react-native

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

'destinationAddresses' =>'88b7a1e8dbf419a2c0835b4f33d06c1a',

1 个答案:

答案 0 :(得分:1)

我已经更新了您的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);
                })
        }
    }

您已经在TextInput中设置了电子邮件,例如 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不是函数。该错误来自updateText()方法。您在setState期间添加了 = ,从而引发了错误。

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