简体   繁体   English

如何在ReactNative中使用FlatList显示数据列表

[英]How to display list of data use FlatList in ReactNative

Hello All, 大家好,

SQLite Table : SQLite表:
Table Name : Users 表名 :用户
Column : user_id,name :user_id,名称

We have try to display user_id and name of User detail into FlatList but I have facing issue into put users object into array and list of array object to display into FlatList. 我们试图将user_id和用户详细信息的名称显示到FlatList中,但是我面临将用户对象放入数组和将数组对象列表显示到FlatList中的问题。

I have show below link of stackoverflow but still I am facing issue : 我已经在stackoverflow的链接下面显示了,但是仍然面临问题:

React Native Sqlite fetch all data in Listview React Native Sqlite获取Listview中的所有数据

import React, { Component } from 'react';
import { Text,
         View,
         Button,FlatList,ListItem,
         TextInput,Alert,
         StyleSheet } from 'react-native';

var SQLite = require('react-native-sqlite-storage')
var db = SQLite.openDatabase({name: 'sqliteexample.db', createFromLocation: '~sqliteexample.db'})
const count = 0;
type Props = {};
export default class HelloWorldApp extends Component<> {

  constructor(props){
      super(props)

      this.state = {
        user_id:'',
        name:'',
        record:[],
        data:{user_id:'',name:''},
        dataSource: [{user_id:'1',name:'a1'},{user_id:'1',name:'a1'},{user_id:'1',name:'a1'}],
      };

      db.transaction(function (txn) {
      txn.executeSql('SELECT * FROM Users', [], function (tx, res) {

         var len = res.rows.length;
         console.log('mylength: ' + len);

         for (let i = 0; i < len; i++) {
           console.log('mylength: ' + res.rows.item(i).name);
           this.setState({dataSource: this.state.dataSource.put(res.rows.item(i).name)});
        }
       });
      });
  }

    onPressInsert (){
      var uid = this.state.user_id;
      var uname = this.state.name;
      console.log('lengths I ' + uid + ' abc ' + uname);
      db.transaction(function (txn) {
       txn.executeSql('INSERT INTO Users (name,user_id) VALUES (:name,:user_id)', [uname,uid]);
       txn.executeSql('SELECT * FROM Users', [], function (tx, res) {
         for (let i = 0; i < res.rows.length; ++i) {
              let row = res.rows.item(i);
              console.log('Select Id a : ' + dataSource.length);
          }
          Alert.alert('Insert Id: ' + uid + ' Name: ' + uname + ' successfully');
       });
      });
    }

    onPressUpdate () {
      var uid = this.state.user_id;
      var uname = this.state.name;
      console.log('lengths U ' + uid + ' abc ' + uname);
      db.transaction(function (txn) {
        txn.executeSql('UPDATE `Users` SET  name=? WHERE user_id=?', [uname,'3']);
        txn.executeSql('SELECT * FROM Users', [], function (tx, res) {
          Alert.alert('Update Id: ' + uid + ' Name: ' + uname + ' successfully');
       });
      });
    }

    onPressDelete () {
      var uid = this.state.user_id;
      var uname = this.state.name;
      console.log('lengths D ' + uid + ' abc ');
      db.transaction(function (txn) {
       txn.executeSql('DELETE FROM `Users` WHERE492 `user_id`=?', [uid]);
       txn.executeSql('SELECT * FROM Users', [], function (tx, res) {
         Alert.alert('Delete Id: ' + uid + ' Name: ' + uname + ' successfully');
       });
      });
    }

    onPressSelect () {
      db.transaction(function (txn) {
       txn.executeSql('SELECT * FROM Users', [], function (tx, res) {
         for (let i = 0; i < res.rows.length; ++i) {
              Alert.alert('Select Id: ' + uid + ' Name: ' + uname + ' successfully');
          }
       });
      });
    }

  render() {

    return (
      <View>
      <TextInput
         style={styles.welcome}
         placeholder="Enter Id"
         editable = {true}
         value = {this.state.user_id}
         onChangeText={(text) => this.setState({user_id:text})}
         maxLength = {30}
       />
       <TextInput
               style={styles.welcome}
               value = {this.state.name}
               placeholder="Enter Full Name"
               editable = {true}
               onChangeText={(text) => this.setState({name:text})}
               maxLength = {30}
             />
         <View>
         <Button
         onPress={this.onPressInsert.bind(this)}
         title="Insert"
         color="#841584"/>
         <Button
         onPress={this.onPressUpdate.bind(this)}
         title="Update"
         color="#841584"/>
         <Button
         onPress={this.onPressDelete.bind(this)}
         title="Delete"
         color="#841584"/>
         </View>
         <FlatList
             data={this.state.dataSource}
             renderItem={({item}) => <Text> Id is :: {item.user_id} Name is :: {item.name}</Text>}
             keyExtractor={(item, index) => index+''}
            />

            <FlatList data={this.state.record}
                         keyExtractor={(x,i) => 1}
                         renderItem={ ({item}) =>
                             <ListItem><Text>{item.name}</Text></ListItem>
                         }
               />
       </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 20,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
 itemBlock: {
   flexDirection: 'row',
   paddingBottom: 5,
 },
 itemImage: {
   width: 50,
   height: 50,
   borderRadius: 25,
 },
 itemMeta: {
   marginLeft: 10,
   justifyContent: 'center',
 },
 itemName: {
   fontSize: 20,
 },
 itemLastMessage: {
   fontSize: 14,
   color: "#111",
 }
});

You initial dataSource is an array of object, but while reading from DB you have considered only the name . 最初的dataSource是一个对象数组,但是从DB读取DB您仅考虑了name You need to put name, user_id into the array. 您需要将name, user_id放入数组中。 You have used put to add data to the array, but put is not an array method, you need to replace put with push , Please consider the following snippet 您已使用put将数据添加到数组,但是put不是数组方法,您需要用push替换put ,请考虑以下代码段

db.transaction(function (txn) {
  txn.executeSql('SELECT * FROM Users', [], function (tx, res) {

     var len = res.rows.length;
     var data = [];
     console.log('mylength: ' + len);

     for (let i = 0; i < len; i++) {
       console.log('mylength: ' + res.rows.item(i).name);
       data.push({ res.rows.item(i).name,  res.rows.item(i).user_id});
     }
     this.setState({dataSource: [...this.state.dataSource, ...data]});
  });

First, data array is being populated with the result from DB, then same is updated into the state , please note, this will append the values inside dataSource . 首先,使用DB的结果填充data数组,然后将其更新为state ,请注意,这会将值appenddataSource内部。 To avoid this and populate only new values into dataSource you will to need change setState statement as 为了避免这种情况,并且仅将新值填充到dataSource您将需要将setState语句更改为

this.setState({dataSource: data});

Hope this will help! 希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM