我已经在数据库中存储了学生id和阅读的书籍数量。现在,我实现了获取学生阅读书籍数量细节的方法。但是函数progressbardata()不返回从查询中获取的数据。我已经尝试在db.transaction()中手动分配一个值并返回它,但没有运气。
你能告诉我我哪里做错了吗?这个方法循环多次。我们如何解决这个问题呢?
import * as Progress from 'react-native-progress';
import { openDatabase } from 'react-native-sqlite-storage';
var db = openDatabase({ name: 'UserDatabase.db' });
let progressbardata = (id) => {
var totalItems=0;
db.transaction((tx) => {
tx.executeSql('SELECT * FROM student where id = ?', [id], (tx, results) => {
totalItems = results.rows.item(0).percent;
return (totalItems);
})
})
}
const _renderContent = (item, index) => {
return (
<View>
<Progress.Bar color='#68FF33' progress={progressbardata(item.id)}/>
</View>
)
}
我的猜测是获取数据的请求是异步的,并且这段代码似乎没有等待响应继续。因此,当获取请求尚未返回值时,代码将继续执行。如果是这种情况,我建议您让请求设置组件的State,并将状态作为Progress的输入。栏组件。这样,当获取请求异步完成时,将设置状态并更新进度条。它看起来像这样:
import * as Progress from 'react-native-progress';
import { openDatabase } from 'react-native-sqlite-storage';
import { useState } from 'react'
var db = openDatabase({ name: 'UserDatabase.db' });
const renderContent = (props) => {
[progress, setProgress] = useState(0)
let progressbardata = (id) => {
var totalItems=0;
db.transaction((tx) => {
tx.executeSql('SELECT * FROM student where id = ?', [id], (tx, results) => {
totalItems = results.rows.item(0).percent;
setProgress(totalItems);
})
})
}
progressbardata(props.id)
return (
<View>
<Progress.Bar color='#68FF33' progress={progress}/>
</View>
)
}