簡體   English   中英

為什么我不能在 ReactNative 的 render 方法內部使用 render 方法外部的函數的返回值?

[英]Why can I not use a return value from a function that is outside the render method, inside the render method in ReactNative?

我在組件內部定義了一個函數,但在 render 方法之外。 它是連接到服務器並檢查登錄憑據的查詢。 該函數確實可以正常工作,查詢也可以,唯一的問題是當我嘗試在組件的 render 方法內的 if 語句中使用函數this._onPressed的返回值時,它似乎沒有正確返回我可以在 if/else 語句中使用的布爾值。

以下是我的前端的完整代碼:

import React, { Component } from 'react';
import axios from 'axios';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Image} from 'react-native';
import { withNavigation } from 'react-navigation';

class LoginForm extends Component {
    constructor(props) {
        super(props)
        this.state = { username:'', password:''}
    }


    _onPress = () => {
        axios.post('http://192.168.137.1:3000/login', {
            username: this.state.username,
            password: this.state.password
        })
        .then(function (response) {
            return response.data;
        })
        .catch(function (error) {
            console.log(error);
        })
    }
    render() {
        return (
            <View style={styles.container}>
                <TextInput style= {styles.input}
                            autoCapitalize="none"
                            onChangeText={(text) => this.setState({username: text})}
                            onSubmitEditing={() => this.passwordInput.focus()}
                            autoCorrect={false}
                            keyboardType={'email-address'}
                            returnKeyType="next"
                            placeholder="Enter Email or Mobile Number"
                            placeholderTextColor='rgba(115,115,115,0.8)'/>

                <TextInput style={styles.input}
                            returnKeyType="go"
                            onChangeText={(text) => this.setState({password: text})}
                            ref={(input)=> this.passwordInput = input} //What does this do???
                            placeholder="Password"
                            placeholderTextColor='rgba(115,115,115,0.8)'
                            secureTextEntry/>
                <TouchableOpacity style={styles.buttonContainer}
                                    onPress={() => this._onPress() == true ? this.props.navigation.navigate('Home') : alert('Login failed')} >
                    <Text style={styles.buttonText}>LOGIN</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.buttonSignupContainer}
                                    onPress={() => this.props.navigation.navigate('Signup')}>
                    <Text style={styles.buttonSignupText}>Sign Up</Text>
                </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        padding: 20,
        marginBottom: 50,
    },
    input: {
        height: 40,
        backgroundColor: 'rgba(225,225,225,0.8)',
        marginBottom: 10,
        padding: 10,
        color: '#737373'
    },
    buttonContainer:{
        backgroundColor: '#38B74C',
        paddingVertical: 15
    },
    buttonText: {
        color: '#fff',
        textAlign: 'center',
        fontWeight: '700',
    },
    buttonSignupContainer: {
        paddingTop:15,
    },
    buttonSignupText: {
        opacity: 0.5,
        textAlign: 'center',
    }
})

export default withNavigation(LoginForm);

這是對我的服務器的查詢請求:

    _onPress = () => {
    axios.post('http://192.168.137.1:3000/login', {
        username: this.state.username,
        password: this.state.password
    })
    .then(function (response) {
        return response.data;
    })
    .catch(function (error) {
        console.log(error);
    })
}

這是我關注的按鈕的 onPress 功能:

<TouchableOpacity style={styles.buttonContainer}
                                onPress={() => this._onPress() == true ? this.props.navigation.navigate('Home') : alert('Login failed')} >
                <Text style={styles.buttonText}>LOGIN</Text>
            </TouchableOpacity>

它總是返回 else 值,即使我 100% 確定它應該返回第一個值。 我還在查詢響應中使用日志語句對其進行了測試,這明確表明函數返回了 true,但是一旦它到達 onPress 道具中的 if 語句,它就不再正確運行。

它不起作用,因為 _onPress 沒有返回一個 Boolean 它正在返回一個Promise 您可以通過以下方式實現您的目標:

onPress={() => this._onPress() == true ? this.props.navigation.navigate('Home') : alert('Login failed')} 

onPress={async () => await this._onPress() == true ? this.props.navigation.navigate('Home') : alert('Login failed')}

然而,即使這不是一個干凈的代碼。 我建議您將整個警報部分移至 _onPress

_onPress = () => {
axios.post('http://192.168.137.1:3000/login', {
    username: this.state.username,
    password: this.state.password
})
.then(function (response) {
    if(response.data)
           this.props.navigation.navigate('Home') 
    else 
           alert('Login failed')
})
.catch(function (error) {
    console.log(error);
})

}

一般來說,最好的做法是將任何語義保留在渲染函數之外。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM