我正在尝试使用反应导航进入新屏幕,但遇到警告[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'this.navigation.navigate')]
。没有引发错误(仅是警告),但该应用程序不会移至下一个屏幕。
我尝试调用包含导航代码的单独功能失败,并使用了箭头功能,但是没有一个选项起作用。
这是我的代码...
import React from 'react';
import {
StyleSheet,
View,
TextInput,
AlertIOS,
} from 'react-native';
import { withNavigation } from 'react-navigation';
import database from '../Database.js';
const db = new database();
class LoginForm extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Access Code"
returnKeyType="go"
onSubmitEditing={text => {
db.isValidCode(text.nativeEvent.text).then(isValid => {
if (isValid) {
this.navigation.navigate('Create')// this throws warning
} else {
AlertIOS.alert(
"We're Sorry...",
'The code you entered was not found in the database! Please contact support for further assistance.'
);
}
}).catch(function(error) {
console.log(error);
throw error;
}) // this "catch" statement didn't fix the warning
}}
/>
</View>
);
}
}
export default withNavigation(LoginForm);
还有数据库文件...
var firebase = require('firebase');
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: "key",
authDomain: "domain",
databaseURL: "url",
storageBucket: "bucket",
});
}
class Database {
constructor() {
this.codesRef = firebase.database().ref('codes');
}
async isValidCode(text) {
let codeIsFound = false;
let identifier = "";
let db_snapshot = await this.codesRef.once('value');
db_snapshot.forEach(code_snapshot => {
if (text == code_snapshot.val().value) {
codeIsFound = true;
identifier = code_snapshot.key;
}
});
return codeIsFound;
};
}
module.exports = Database;
我不确定为什么导航不起作用。当该功能与使用该文件的文件位于同一文件中时,一切工作正常,并且更加简单。感谢所有帮助/指针!
答案 0 :(得分:2)
您需要使用:
this.props.navigation.navigate('Create')
代替:
this.navigation.navigate('Create')
因为withNavigation
将navigation
添加到了组件的属性,而不是组件本身。