登录后无法浏览主屏幕

时间:2019-02-04 13:01:02

标签: javascript reactjs react-native ecmascript-6 react-redux

Please find attached log 登录后我试图进入主屏幕。 每当我输入错误的userid警报时,都会出现错误的凭据消息,但是当我输入正确的信息时,就会出现错误“ [TypeError:未定义不是对象(正在评估'_this.props.navigation')”“

// This is 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',
    },

  });

下面的代码是我输入用户名并通过的ui的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'

}

})

//以下是我的脚本

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 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
            }

            } )  )
          }

请帮助。.谢谢

2 个答案:

答案 0 :(得分:0)

这是因为您的LoginApi中没有this.props

<TouchableOpacity style={styles.button}onPress={() => 

Login(this.state.username,this.state.password, this)}> //pass this here

          <Text style={styles.buttonText}>Login</Text>
      </TouchableOpacity>

Login内部:

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

,然后您可以使用:

self.props.navigation.navigate('HomeScreen');

更新:

import { withRouter } from 'react-router'
class FormImpl 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 Form = withRouter(FormImpl);
export default Form

内部LoginApi:

self.props.history.push('/ home');

答案 1 :(得分:0)

例如,您的App.js中是否有类似的东西?

import Navigator from "./Navigator";

const AppNavigator = StackNavigator({ Navigator: { screen: Navigator }});

export default (props) =>
  <Root>
    <AppNavigator />
  </Root>
;

,然后在您的Navigator.js内:

const Navigator = StackNavigator({
  Login: { screen: Login, navigationOptions: navigationOptions },
  ...
});