错误:未定义不是 ReactNative 中的对象(评估“db.transaction") [英] Error : undefined is not an object (evaluating 'db.transaction') in ReactNative
问题描述
我正在遵循从现有 iOS 数据库填充值的所有说明:链接
I am following all the instructions for populating value from existing database for iOS from this :link
并使用以下代码:
import SQLite from 'react-native-sqlite-storage';
var db;
export default class App extends Component<Props> {
errorCB(err) {
console.log("SQL Error: " + err);
};
successCB() {
console.log("SQL executed fine");
};
openCB() {
console.log("Database OPENED");
};
openDB() {
db = SQLite.openDatabase({name : "sqliteexample", createFromLocation : 1}, this.openCB, this.errorCB);
}
populateDB() {
db.transaction((tx) => {
tx.executeSql("SELECT * FROM Users", [], (tx, results) => {
console.log("Query completed");
// Get rows with Web SQL Database spec compliance.
var len = results.rows.length;
console.log('len' + len)
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
console.log(`User: ${row}`);
}
});
});
}
render() {
return (
<View style={styles.container} >
<Button onPress={this. openDB}
title="open Database"
color="#841584"/>
<Button onPress={this. populateDB}
title="Get Data"
color="#841584"/>
</View>
);
}
}
我收到此错误:
undefined 不是一个对象(评估 'db.transaction')
undefined is not an object (evaluating 'db.transaction')
但是在控制台中成功打开数据库得到以下消息:
But Successfully open database getting following message in console:
2018-06-08 11:43:40.678[信息][tid:com.facebook.react.SQLiteQueue][SQLite.m:255] 打开 cb完成 2018-06-08 11:43:40.679[信息][tid:com.facebook.react.JavaScript] 数据库打开:sqliteexample2018-06-08 11:43:40.679165+0530 FlatListAppDemo[1018:61832] 打开 cb完成 2018-06-08 11:43:40.679220+0530FlatListAppDemo[1018:61820] 数据库打开:sqliteexample
2018-06-08 11:43:40.678 [info][tid:com.facebook.react.SQLiteQueue][SQLite.m:255] open cb finished ok 2018-06-08 11:43:40.679 [info][tid:com.facebook.react.JavaScript] DB opened: sqliteexample 2018-06-08 11:43:40.679165+0530 FlatListAppDemo[1018:61832] open cb finished ok 2018-06-08 11:43:40.679220+0530 FlatListAppDemo[1018:61820] DB opened: sqliteexample
请帮我解决这个问题.提前致谢.
Please Help me to solve this issue. Thanks in advance.
推荐答案
所以我认为这可能只是时间问题.获取数据库对象的最安全方法是在成功回调中,如果在 openDatabase 中一切顺利,它将接收一个有效的 db 对象.所以将您的代码更改为此并尝试...
so I think it could be just timing issue. The safest way to obtain a database object would be inside the success callback which will receive a valid db object if all goes well in openDatabase. so change your code to this and try it...
openCB(myDB) {
console.log("Database OPENED");
db = myDB;
};
openDB() {
SQLite.openDatabase({name : "sqliteexample", createFromLocation : 1}, this.openCB, this.errorCB);
}
这篇关于错误:未定义不是 ReactNative 中的对象(评估“db.transaction")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!