Я создаю страницу входа в реагирующую систему, где я создаю три страницы: Login.js - это главная страница, на которую я импортирую оба компонента, а компоненты - Form.js и Loginapi.js.В Form.js все части пользовательского интерфейса, такие как имя пользователя, пароль и кнопка и нажатие кнопки, которую я вызываю, логический скрипт 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',
},
});
Приведенный ниже код - это 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стр.