列出数据库中的项目

时间:2018-04-12 20:24:44

标签: react-native

我正在使用SQLite,我可以获取数据库的项目,但我无法在Text组件上编写项目:

<View style={{flexDirection:'row', flexWrap:'wrap'}}>
{
db.transaction((tx) => {
  var sql = 'SELECT * FROM flor where nomePopular like \'%brom%\''
  tx.executeSql(sql, [], (tx, results) => {

    var len = results.rows.length;
    for (let i = 0; i < 10; i++) {
      let row = results.rows.item(i);
      alert(row.id) //THE ALERT WORK
      {<Text>row.id</Text>} //TEXT NOT WORKS
    }
  });
});
}
</View>

警报正常,但文字不起作用:/

1 个答案:

答案 0 :(得分:1)

我对SQL并不了解,但我认为db.transaction会返回一个transaction对象,而这个对象无法用于呈现JSX。

因此,您需要做的是将其移至单独的模块

state = {
  rows: [] // Initially an empty array
}

getTransactionResults = () => {
db.transaction((tx) => {
  var sql = 'SELECT * FROM flor where nomePopular like \'%brom%\''
  tx.executeSql(sql, [], (tx, results) => {

    var len = results.rows.length;
    this.setState({rows: results.rows.raw()})
  });
});
}

render () {
  const transaction = this.getTransactionResults() //<== Call here to initiate transaction
  return (
    <View style={{flexDirection:'row', flexWrap:'wrap'}}>
      {
       this.state.rows.map((row) => <Text key={row.id}>{row.id}<Text>)
      }
    </View>
   )
}