[英]How to fix 'undefined is not an object' error in react native
我試圖以更有條理的方式移動我的本機應用程序代碼。 file with a Database class and all of the functions. 最初,我將所有firebase函數都放在我使用它們的文件中,但現在我想在多個地方使用它們,所以我創建了一個文件,其中包含Database類和所有函數。 但是出於某種原因,每當我嘗試使用新類中的一個函數時,我都會收到錯誤"undefined is not an object (evaluating 'this.codesRef.once')"
請幫忙!
到目前為止,我已嘗試使用箭頭函數,構造函數和以不同方式導入firebase,但都無濟於事。 我對此很難過。
看看代碼...
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;
//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文件之前,一切都工作正常。 任何幫助是極大的贊賞!
您的checkCode
函數是static
。 您無法在靜態方法中訪問this
上下文。 在你的/project/src/components/Database.js中改變它:
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");
);
}
};
在/project/src/components/forms/KeyForm.js中訪問此函數時
import firbaseDB from '../Database.js';
const db = new firbaseDB();
...
其余的代碼就是這樣。 干杯。
嘗試在您的類中使用構造函數:
class Database {
constructor() {
this.codesRef = firebase.database().ref("codes");
}
//...
}
也許你必須這樣做
class Database {
constructor(props) {
super(props);
this.codesRef = firebase.database().ref("codes");
}
//...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.