首页 > React native 如何实现滚动无限加载?

React native 如何实现滚动无限加载?

如题目,我用了ListView这个组件,但是一直出问题:

var MessageList = React.createClass({
  getInitialState: function() {
    return {
      dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
      isLoadingTail: false
    }
  },
  componentDidMount: function () {
    this._messages = [];
    this.setState({
        dataSource: this.getDataSource(this.props.messageList)
    });
  },
  getDataSource: function (messages):ListView.DataSource {
      this._messages = this._messages.concat(messages);
      return this.state.dataSource.cloneWithRows(this._messages);
  },
  _onEndReached: function () {
      console.log('onEndReached', this.state.isLoadingTail);
      if (this.state.isLoadingTail) {
          // We're already fetching
          return;
      }

      this.setState({
          isLoadingTail: true
      });

      this.setState({
          isLoadingTail: false,
          dataSource: this.getDataSource(this.props.messageList)
      });
  },
  _renderRow: function(rowData, sectionID, rowID){
    return (
      <Text>{rowData}</Text>
    )
  },
  render: function() {
    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this._renderRow}
        onEndReached={this._onEndReached}
        style={MessageListStyle.container}
        />
    );
  }
});

问题在 this.props.messageList 在 render 输入是不为空的数组,但是在componentDidMount函数中却变成了一个空的数组,请问这是怎么回事啊?应该怎么解决?

期待你的帮忙。


this.props.messageList 和 this.props.messages.messageList 是故意携程不一样的的吗?


你不应当只在componentDidMount函数中去为列表加载新的数组数据,因为你不知道这个时候,this.props.messageList里是否有数据。你自己也说了“数据是父级组件中的state传递下来的props,初次为空”。如果你说的是真的,那么在这个时候,极有可能this.props.messageList中没有数据。
你应当在componentWillReceiveProps(object nextProps)函数中对nextProps进行判断,在这里可以判断nextProps.messageList里是否被父组件放入了新数据(将nextProps.messageList与this.props.messageList进行比较)。如果放入了新数据,将数据放入列表中。


@cnsnake11

我的数据是父级组件中的state传递下来的props,初次为空,然后父级state会发生变化从而,自动更新了props。


用这个插件试试 :地址


componentDidMount 改成 componentWillMount 试一下

【热门文章】
【热门文章】