可以在react-native中访问数组的内容

时间:2019-05-28 13:56:06

标签: javascript sqlite react-native

我正在尝试从React-Native(android)中的SQLite数据库获取数据。该函数返回一个包含数据的数组。 如果我尝试将阵列记录到控制台,则可以正常工作,但是当我将阵列的长度记录到控制台时,它突然显示“ 0”。

功能:

getActByButton(category) {
        return new Promise((resolve) => {
            const activities = [];
            const request = 'SELECT activity FROM activity_button WHERE category = ? AND activity IS NOT NULL';
            this.initDB().then((db) => {
                db.transaction((tx) => {
                    tx.executeSql(request, [category]).then(([tx, results]) => {
                        //console.log('Query COMPLETED');
                        var len = results.rows.length;
                        for (let i = len; i > 0; i--) {
                            activities.push(results.rows.item(i - 1));
                        }
                        resolve(activities);
                    })
                }).then((result) => {
                    this.closeDatabase(db);
                })
            })
        })
    }

    getIconByAct(activity_ids) {
        return new Promise((resolve) => {
            const icons = [];
            const request = 'SELECT name, icon FROM activity WHERE id = ?';
            this.initDB().then((db) => {
                db.transaction((tx) => {
                    for (let id in activity_ids) {
                        tx.executeSql(request, [id]).then(([tx, results]) => {
                            console.log('Query COMPLETED');
                            var len = results.rows.length;
                            let icon = results.rows.item(0).icon;
                            let description = results.rows.item(0).name;
                            icons.push({ icon, description });
                        })
                    }
                    resolve(icons);
                }).then((result) => {
                    this.closeDatabase(db);
                })
            })
        })
    }

函数调用:

db.getActByButton(this.props.category).then((data) => {
    result_ids = data;
}).then(() => {
    db.getIconByAct(result_ids).then((data) => {
        console.log('DATA:');
        console.log(data);
        console.log(data.length);
        console.log(data[1]);
    })
})

控制台: enter image description here

这怎么可能? 我该如何解决?

1 个答案:

答案 0 :(得分:-1)

尝试一下:

db.getActByButton(this.props.category).then((data) => {
    result_ids = data;
}).then(() => {
    db.getIconByAct(result_ids).then((data) => {
        console.log(JSON.stringify(data));
        console.log(JSON.stringify(data.length));
    })
})