簡體   English   中英

如何解決React Native中的導航問題(TypeError:undefined不是一個對象(評估'_this.props.navigation))

[英]How to fix navigation problem in React Native (TypeError: undefined is not an object (evaluating '_this.props.navigation)

我在react-native中創建一個登錄頁面,在其中創建三個頁面:Login.js-這是我要導入兩個組件的主頁,而組件是-Form.js和Loginapi.js。 在Form.js中,所有UI部分,例如用戶名,密碼和按鈕,然后在按鈕上單擊“我正在調用”,Loginapi.js邏輯腳本-成功登錄后,我必須轉到HomeScreen頁面。 但我收到TypeError: undefined is not an object (evaluating '_this.props.navigation) '

我已經嘗試了很多方法來解決這個問題。 通常,我可以導航到所有屏幕,但是在這里我正在使用組件的位置,並且在成功登錄響應后,它不會移至下一頁。

// This is the main login page. 

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,StatusBar} from 'react-native';
import Logo from '../component/Logo';
import Form from '../component/Form';

export default class Login extends Component {

    render() {

        return(

            <View style ={styles.container}>
            <Logo/>
            <Form  navigation = {this.props.navigation} 
/>
            <View style={styles}>
            </View>
            </View>

        )
    }
}

const styles = StyleSheet.create({
    container: {
      backgroundColor: '#ffffff',
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },

  });

下面的代碼是用於IO的form.js,我在其中輸入用戶名和密碼。

import React, {Component} from 'react';
import {TextInput,Platform,Alert,AsyncStorage, StyleSheet, Text, View,StatusBar,Image,TouchableOpacity} from 'react-native';

import {Login} from '../api/Loginapi'
  export default class Form extends React.Component
  {

    constructor(){
      super()
      this.state={
        username:"",
        password:"",
        postString: "",
      }
    }

    render() {

        return(
            <View style={styles.container}>

    <TextInput   style={styles.inputBox}
     underlineColorAndroid='rgba(0,0,0,0)'
      placeholder="username"
      placeholderTextColor="#000000"
      onChangeText={(username) => this.setState({username})}/>

   <TextInput   style={styles.inputBox}
     underlineColorAndroid='rgba(0,0,0,0)'
      placeholder="password"
      secureTextEntry={true}
      placeholderTextColor="#000000"
      onChangeText={(password) => this.setState({password})}/>

      {/* <TouchableOpacity style={styles.button}onPress={() => this.onClickListener('login')}>
          <Text style={styles.buttonText}>Login</Text>
      </TouchableOpacity> */}

<TouchableOpacity style={styles.button}onPress={() => Login(this.state.username,this.state.password,this)}>
          <Text style={styles.buttonText}>Login</Text>
      </TouchableOpacity>

</View>
        )
    }
}

const styles =StyleSheet.create({

container :{
    flex :1,
    justifyContent :'center',
    alignItems:'center'
},
inputBox:{
    width:300,
    borderColor: '#48BBEC',
    backgroundColor: '#F8F8FF',
    borderRadius:25,
    paddingHorizontal:16,
    fontSize:16,
    color:'#000000',
    marginVertical:10,

},
button:{
    width:300,
    backgroundColor:'#4169E1',
    borderRadius:25,
    marginVertical:10,
    paddingVertical:16
},

buttonText:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'

}

})

// Below is my script 

export const  Login = (username,password,self) => {

  var postString = ':xxxxxxxx:21:UN#'+username+':PW#'+password+':';
            var l = postString.length + 2;
            var newPostString = l + postString;
            var newL = newPostString.length;
            if (newL !== l) {
              l++;
            }
            postString = l + postString;

            fetch('http://178.128.19.107:8080/iot-server/JnarkUserAPI', {
              method: 'POST',
              body: postString
            })

            .then( (response) => {
              console.log("Posted:" + postString);
             return response.json();
            })

            .then ( (res => {

              try {

              if (res.success == "true") {
                AsyncStorage.setItem('username', res.userName);
                AsyncStorage.setItem('uEmail', res.email);
                AsyncStorage.setItem('uPh', res.phNum);
                AsyncStorage.setItem('uPlevel', res.privLevel);
                AsyncStorage.setItem('uPwd', res.password);

// here I am getting "[TypeError: undefined is not an object (evaluating '_this.props.navigation')"

                self.props.navigation.navigate('HomeScreen');
               // this.props.navigation.replace('HomeScreen');
               // this.props.navigation.navigate('HomeScreen');

              }
              else {
                Alert.alert("Alert Incorrect Credentials");

              }
            } catch (error) {
              console.log("hello",error);
              // Error saving data
            }

            } )  )
          }

我希望從我的Loginapi.js頁面轉到HomeScreen.js頁面。

首先,您應該檢查所使用的導航庫是否正確安裝。 您是否正在使用react-navigationreact-native-router-flux ...?

另外,我認為您也應該發布路線腳本聲明,以便我們為您提供幫助。 否則,我們不知道您可以使用哪些方法瀏覽屏幕。

我認為您的form.js中的 onPress函數不正確。

<TouchableOpacity style={styles.button}onPress={() => Login(this.state.username,this.state.password,this)}>

您應該改為具有導航到“登錄”組件的功能,例如

onPress={() => this.props.navigation.navigate('Login', {username: this.state.username, password: this.state.password})}

並傳遞用戶名密碼作為參數。

我也想避免這種情況傳遞到嵌套組件...

暫無
暫無

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

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