react native react-native-sqlite-storage 不返回结果
2018-07-23
4616
我使用来自 react-native-sqlite-storage 的 SQLite 数据库
我没有在警报中显示结果
它显示
undefined
我也尝试不使用 await 和 async
MainFile
import DBHelper from './DBHelper.js';
export default class MainFile extends Component {
componentDidMount() {
this.dbTransaction();
}
dbTransaction = async () => {
var value = await DBHelper.getWatchList()
alert(value)
}
.....
}
DBHelper
import React, {Component} from 'react';
var SQLite = require('react-native-sqlite-storage');
var dbName = "test.db";
var tableName = "tableName";
const DBHelper = {
getWatchList: () => {
var db = SQLite.openDatabase({name : dbName, createFromLocation : 1}, openCB,errorCB);
db.transaction( (tx) => {
tx.executeSql("select * from " + tableName,
[], (tx, results) => {
console.log("\n\nQuery completed\n");
var resultItemIdArr = new Array();
for (let i = 0; i < results.rows.length; i++) {
resultItemIdArr.push(results.rows.item(i).itemId);
console.log(results.rows.item(i).itemId);
}
return resultItemIdArr;
});
});
},
}
const errorCB = (err) => {
console.log("SQL Error: " + err);
}
const successCB = () => {
console.log("SQL executed fine");
}
const openCB = () => {
console.log("Database OPENED");
}
export default DBHelper;
我想在警报中打印 resultItemIdArr 值
1个回答
您在此处使用回调
db.transaction((tx) => {
,因此您将在回调中返回
resultItemIdArr
。如果该库不支持承诺,您应该这样做:
getWatchList: (callback) => {
var db = SQLite.openDatabase({name : dbName, createFromLocation : 1}, openCB,errorCB);
db.transaction( (tx) => {
tx.executeSql("select * from " + tableName,
[], (tx, results) => {
console.log("\n\nQuery completed\n");
var resultItemIdArr = new Array();
for (let i = 0; i < results.rows.length; i++) {
resultItemIdArr.push(results.rows.item(i).itemId);
console.log(results.rows.item(i).itemId);
}
callback(resultItemIdArr);
});
});
},
并像这样调用
getWatchList
:
dbTransaction = () => {
DBHelper.getWatchList(value=>{
alert(value)
})
}
LHIOUI
2018-07-23