我正在使用 react native 并且我刚刚将一些数据库函数迁移到了一个单独的文件,而不是仅仅将它们放在我需要它们的文件中(我已经开始需要在多个文件中使用相同的函数,我宁愿有它们都在一个地方)。问题是,应该将一次性键与数据库中的键进行比较的函数总是返回undefined。
我尝试过返回函数而不是布尔值,并尝试使用“async/await”关键字(我对此知之甚少)。
这是我的代码...
/project/src/components/Database.js
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');
}
isValidCode(text) {
let codeIsFound = false;
let identifier = "";
this.codesRef.once('value', (db_snapshot) => {
db_snapshot.forEach((code_snapshot) => {
//console.log(text, code_snapshot.val().value, text == code_snapshot.val().value);
if (text == code_snapshot.val().value) {
codeIsFound = true;
identifier = code_snapshot.key;
}
});
//console.log(codeIsFound); // this is correct
return codeIsFound; // this always returns undefined
});
};
}
module.exports = Database;
/project/src/components/forms/KeyForm.js
import React from 'react';
import {
StyleSheet,
View,
TextInput,
} 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
style={styles.input}
placeholder="Access Code"
returnKeyType="go"
onSubmitEditing={text => {console.log(db.validCode(text.nativeEvent.text))}} // "undefined"
autoCapitalize="none"
autoCorrect={false}
/>
</View>
);
}
}
const styles = StyleSheet.create({\
// yay styles :)
});
export default withNavigation(LoginForm);
每当我在 firebase “once” 函数之后放置一个 return 语句时,它都会返回一个布尔值,但由于某种原因,它总是错误的。任何帮助是极大的赞赏!
解决这个问题:每当我在 firebase “once” 函数之后放置一个 return 语句时,它都会返回一个布尔值,但由于某种原因,它总是错误的。
通过删除.once()
方法代码,您可以清楚地看到为什么会这样。代码完全按照如下方式执行。由于该.once()
方法的异步性质,该return
语句在.once()
解析(完成)之前执行。
isValidCode(text) {
let codeIsFound = false;
let identifier = "";
// .once() goes here
return codeIsFound;
};
你的直觉是关于 async/await 的一个很好的直觉。要解决您的问题,请执行以下操作:
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;
};
然后,该函数将返回一个将被解析(或拒绝)的承诺。因此,要使用此代码,请执行以下操作:
isValidCode('something').then(result => {
/* use result here */
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句