FlatList不显示数据

时间:2019-02-02 08:04:51

标签: react-native react-native-flatlist

我的问题似乎重复了,但事实并非如此。 我正在尝试从本地sqlite获取一张表,并通过一个列表显示它。但显示未定义!

这是模拟器上输出的屏幕截图: https://imgur.com/a/Ds6xMF8

这是我的代码:

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  ToastAndroid,
  ListView,
  ActivityIndicator,
  FlatList,
  } from 'react-native';


var SQLite = require('react-native-sqlite-storage')
var db = SQLite.openDatabase({name: 'test.db', createFromLocation: '~sqliteexample.db'})

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      petname: "",
      owner: "",
      record: []
    };


  db.transaction((tx) => {
    tx.executeSql('SELECT * FROM pet', [], (tx, results) => {
      var len = results.rows.length;
      for (let i = 0; i < len; i++) {
        let row = results.rows.item(i);
        record = this.state.record.slice()
        record.push(row.petname)
        this.setState({ record: record })
}
    });
});

  }

  render() {
    return (
      <View style={styles.container}>
        <Text>SQLite Example</Text>     
        <FlatList 
              data={this.state.record} 
              keyExtractor={((item, index) => "itemNo-" + index)}                            renderItem={({item}) => (
              <View>
                  <View>
                    <Text>{'this owner:  ' + item.owner}</Text>
                  </View>
                  <View>
                    <Text>{'this petmname:    '+ item.petname}</Text>
                </View>
              </View> 
        )
    }
/>
          </View>
    );
  }
}

请告诉我我做错了什么? 谢谢。

1 个答案:

答案 0 :(得分:2)

我认为问题出在下一行:

record.push(row.petname)

您要推送字符串row.petname,然后稍后尝试检索其属性-这是不正确的,因为它没有它们。

尝试将下一行替换为下一行:

record.push(row)

此外,.slice()的用途是什么: record = this.state.record.slice()吗?