繁体   English   中英

ReactNative ListView的初始状态

[英]ReactNative listview initial state

我已经开始开发React本机应用程序,并且列表视图的初始化有问题。

我正在使用react-native-db-models插件来存储和检索我的数据

问题是我想在我的react listview的getInitialState函数中获取数据,并且需要调用一个回调函数。

这是我从db检索数据的类的代码:

'use strict';

var React = require('react-native');

var DB = require('./Database');

var DBEvents = require('react-native-db-models').DBEvents;

class BarcodeDAO {
  get_all_barcodes(success) {
    DB.barcodes.get_all(success);
  }
}

module.exports = BarcodeDAO;

这是我的listview代码:

'use strict';

var React = require('react-native');

var {
  AppRegistry,
  Text,
  ListView,
  View,
} = React;

var BarcodeDAO = require('./BarcodeDAO');


var BarcodeList = React.createClass({
  statics: {
    title: '<ListView> - Simple',
    description: 'Performant, scrollable list of data.'
  },

  getInitialState: function() {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

    var barcodeDAO = new BarcodeDAO();

    barcodeDAO.get_all_barcodes(function(result) {
       var data = [];
       for(var i = 1; i <= result.totalrows; i++) {
         console.log(result.rows[i].barcode.value);
         data[i-1] = result.rows[i].barcode.value;
       }
       //THIS IS WHERE I DON'T KNOW HOW TO PASS THE VALUE THE THE return of the getInitialState function..
       //self.state.dataSource.cloneWithRows(data);
       //self.getDataSource(self,data);
    });

    return {
      dataSource: ds.cloneWithRows({??????})
    };
  },

  },

  getDataSource: function(self, barcodes: Array<any>): ListView.DataSource {
    console.log("update");
    return self.state.dataSource.cloneWithRows(barcodes);
  },

  render: function() {
    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={(rowData) => <Text>{rowData}</Text>}
      />
    );
  },
});

module.exports = BarcodeList;

我是React和JavaScript的新手,所以也许很明显,但我不知道该怎么做。

提前致谢

因为您需要异步获取数据,所以应该这样设置初始数据:

getInitialState() {
  dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
}

在componentDidMount中,您应该运行获取数据的函数,一旦拥有数据,您应该执行类似的操作

this.setState({dataSource: state.dataSource.cloneWithRows(arrayOfBarcodes)})

您的列表将自动使用正确的数据重新呈现。

您可以(并且应该应该)在获取数据时显示微调框。 因此,只需将初始状态添加为loaded: false ,然后从数据库中获取数据时,将load设置为true:

this.setState({
  dataSource: state.dataSource.cloneWithRows(arrayOfBarcodes),
  loaded: true
})

然后在您的render方法中做类似

render() {
  if (this.state.loaded) {
     this.renderTheListView()
  }
  else {
     this.renderLoadingIndicator()
  }
}

暂无
暂无

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

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