【发布时间】:2019-10-05 20:08:03
【问题描述】:
我正在尝试将我的 react-native 应用程序代码以更结构化的方式移动。最初,我将所有的 firebase 函数放在我使用它们的文件中,但现在我想在多个地方使用它们,所以我创建了一个 Database.js 文件,其中包含一个 Database 类和所有的功能。但出于某种原因,每当我尝试使用新类中的某个功能时,都会收到错误 "undefined is not an object (evaluating 'this.codesRef.once')" 请帮助!
到目前为止,我尝试过使用箭头函数、构造函数以及以不同方式导入 firebase,但均无济于事。我对这个很困惑。
看看代码... (/project/src/components/forms/KeyForm.js)
import React from 'react';
import { StyleSheet, View, TextInput } from 'react-native';
import db from '../Database.js';
class LoginForm extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Access Code"
returnKeyType="go"
onSubmitEditing={text => {db.checkCode(text.nativeEvent.text)}}
/>
</View>
);
}
}
const styles = StyleSheet.create({ // stylesheet
// yay styles :)
});
export default LoginForm;
(/project/src/components/Database.js)
//import * as firebase from "firebase";
var firebase = require('firebase');
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: "key",
authDomain: "domain",
databaseURL: "url",
storageBucket: "bucket",
});
}
class Database {
codesRef = firebase.database().ref('codes');
static checkCode(text) {
let codeIsFound = false;
this.codesRef.once('value', (db_snapshot) => { // this won't work
db_snapshot.forEach((code_snapshot) => {
if (text == code_snapshot.val().value) {
codeIsFound = true;
identifier = code_snapshot.key;
}
});
});
if (codeIsFound) {
//this.deleteCode(identifier);
console.log("code found");
this.props.navigation.navigate('Create'); // side-question => how can i get this working in Database.js? Do i need to use withNavigation?
} else {
console.log("code not found");
);
}
};
}
module.exports = Database;
澄清一下,在我尝试将函数迁移到 Database.js 文件之前,一切正常工作 100%。非常感谢任何帮助!
【问题讨论】:
标签: javascript firebase react-native ecmascript-6 firebase-authentication