从数据库助手类向组件返回数据

时间:2018-11-12 07:57:28

标签: sqlite react-native

  

我正在使用sqlite,并且创建了一个db helper类。我没有从组件内部的该类获取数据,但是如果我在db helper内部进行了安慰,则它工作正常,但在组件中却无法正常工作。我正在提供我的代码:-

     

Cartdb.js。 (帮助程序类)

var SQLite = require('react-native-sqlite-storage')
db = SQLite.openDatabase('predefine.db', "1.0", "Predefine", -1);
class CartDB {
    constructor(){

    }
    totalItems = 0;
    checkCountOfProduct(){
        query = "SELECT SUM(count) AS product_count FROM Predefinedcart";
       db.transaction((tx) => {
            tx.executeSql(query, [], (tx, results) => {
                console.log(results.rows.item(0).product_count)
                this.totalItems = results.rows.item(0).product_count;
                return this.totalItems;
            }, function (tx, error) {
                console.log('SELECT error: ' + error.message);
            });
        })
    }
}

export default new CartDB();
  

组件中的代码

import CartDB from '../../../library/CartDB';
class PredefinedLayout extends React.Component{
 constructor(props){
   super(props);
   console.log(CartDB.checkCountOfProduct());
 }


}

如何在这里获取数据?预先感谢。

1 个答案:

答案 0 :(得分:1)

它是一个异步操作,这意味着它是一个承诺。最好的方法是将回调传递给该函数或将数据库操作作为promise和chain返回。一些关于Promises的javascript文档在这里。

带有回调:

class CartDB {
constructor(){

}
totalItems = 0;
checkCountOfProduct(callback){
    query = "SELECT SUM(count) AS product_count FROM Predefinedcart";
   db.transaction((tx) => {
        tx.executeSql(query, [], (tx, results) => {
            console.log(results.rows.item(0).product_count)
            this.totalItems = results.rows.item(0).product_count;
            callback(this.totalItems)
        }, function (tx, error) {
            console.log('SELECT error: ' + error.message);
        });
    })
}
}

,然后在Comp中调用: CartDB.checkCountOfProduct(count => console.log(count));

有前途:

class CartDB {
constructor(){

}
totalItems = 0;
checkCountOfProduct(){
    query = "SELECT SUM(count) AS product_count FROM Predefinedcart";
   return new Promise((resolve, reject) => db.transaction((tx) => {
        tx.executeSql(query, [], (tx, results) => {
            console.log(results.rows.item(0).product_count)
            this.totalItems = results.rows.item(0).product_count;
            resolve(this.totalItems);
        }, function (tx, error) {
            reject(error);
        });
    }))
}
}

,在Comp中,您致电:CartDB.checkCountOfProduct().then(count => console.log(count));