如何解决React Native中的导航问题(TypeError:undefined不是一个对象(评估'_this.props.navigation))

时间:2019-02-05 07:28:53

标签: javascript reactjs react-native react-redux

我要在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页面。

2 个答案:

答案 0 :(得分:0)

首先,您应该检查所使用的导航库是否正确安装。您在使用react-navigationreact-native-router-flux,...吗?

此外,我认为您也应该发布路线脚本声明,以便我们为您提供帮助。否则,我们不知道您可以使用哪些方法浏览屏幕。

答案 1 :(得分:0)

我认为 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})}

并将用户名密码作为参数传递。

我还避免将 this 传递给嵌套组件...