如何在React Native中的_onPress方法中强制更新listView

时间:2017-04-27 19:18:41

标签: android listview react-native

我有一个小的API前端,它可以正常工作,除了在调用_onPress方法更新api数据后更新ListView。

import React, {Component} from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView,
  Image,
  RefreshControl,
  TouchableOpacity
} from 'react-native';
import Header from './Header';


export default class api extends Component {
  constructor(props) {
    super(props);

    this._onPress = this._onPress.bind(this);
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      refreshing: false,
      pageNumber: 0,
      flightsData: ds.cloneWithRows([]),
    };
  }


  fetchFlightsData() {
    /*removed for brevity*/
  }

  _onPress() {
    this.setState({refreshing: true});
    this.setState({pageNumber: this.state.pageNumber + 1});
    this.fetchFlightsData();
    this.setState({refreshing: false});
  };

  _onRefresh() {
    this.setState({pageNumber: 0});

    this.fetchFlightsData()
  }


  componentDidMount() {
    this.fetchFlightsData();
  }

  render() {

    return (

      <ListView
        renderHeader={() => <Header />}
        renderFooter={() => this.renderFooter() }
        dataSource={this.state.flightsData}
        renderRow={this.renderRow}
        style={styles.container}
        refreshControl={
          <RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={this._onRefresh.bind(this)}
          />
        }
      />
    );
  }

  renderFooter() {

    return (

      <View style={styles.container}>
        <TouchableOpacity style={styles.button} onPress={() => this._onPress()}>
          <Text style={styles.text}>Load More</Text>
        </TouchableOpacity>
      </View>
    );
  }

  renderRow(rowData) {
    return (
/*removed for brevity*/
);
  }

}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#f2f2f2',
  },
  thumb: {
    backgroundColor: '#ffffff',
    marginBottom: 5,
    elevation: 1
  },
  img: {
    height: 300
  },
  txt: {
    margin: 10,
    fontSize: 16,
    textAlign: 'left'
  },
  button: {
    borderColor: '#8E8E8E',
    borderWidth: StyleSheet.hairlineWidth,
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
});


AppRegistry.registerComponent('api', () => api);

当调用onPress方法时,它按预期刷新数据,但不更新ListView,直到你第二次按下按钮,它会显示第一个的新数据>按。

_onRefresh()方法的工作原理类似。

1 个答案:

答案 0 :(得分:1)

setState不会立即更改状态,如果您想在状态更新后执行某些操作,则必须使用可选的第二个参数:

_onPress() {
  this.setState({ refreshing: true, pageNumber: this.state.pageNumber + 1 }, 
  () => this.fetchFlightsData());
  this.setState({refreshing: false}); //This part should probably go inside fetchFlightsData once you retrieve the data.
};