React Native ListView - rowHasChanged不会触发

时间:2015-11-23 11:49:50

标签: react-native

我正在尝试在React Native中实现无限滚动。以下是该组件的来源:

var React = require('react-native');
var server = require('../server');
var Post = require('./Post');
var SwipeRefreshLayoutAndroid = require('./SwipeRefreshLayout');
var backEvent = null;
var lastPostId = "";
var isLoadingMore = false;
var isLoadingTop = false;
var onEndReachedActive = false;

var {
    StyleSheet,
    ListView,
    View,
    Text,
    Image,
    ProgressBarAndroid,
    BackAndroid
} = React;

class Stream extends React.Component {

constructor(props) {
    super(props);
    this.ds = new ListView.DataSource({
        rowHasChanged: (row1, row2) => {
            console.log("rowHasChenged FIRED!!");
            return false;
        }
    });

    this.state = {
        dataSource: this.ds.cloneWithRows(['loader']),
        hasStream: false,
        posts: []
    };

}

componentDidMount() {

    BackAndroid.addEventListener('hardwareBackPress', () => {
        this.props.navigator.jumpBack();
        return true;
    }.bind(this));

    server.getStream('', '', 15).then((res) => {

        lastPostId = res[res.length-1].m._id;

        this.setState({
            posts: res,
            hasStream: true,
            dataSource: this.ds.cloneWithRows(res)
        }, () => onEndReachedActive = true);
    })
}

onRefresh() {
    var posts = this.state.posts;
    var firstPost = posts[0].m._id;

    console.log(this.state.dataSource._rowHasChanged);

    isLoadingTop = true;

    server.getStream('', firstPost, 4000)
        .then(res => {
            console.log(posts.length);
             posts = res.concat(posts);
             console.log(posts.length);
             this.setState({
                dataSource: this.ds.cloneWithRows(posts),
                posts
             }, () => {
                this.swipeRefreshLayout && this.swipeRefreshLayout.finishRefresh();
                isLoadingTop = false;
             });
        }).catch((err) => {
            isLoadingTop = false;
        })

}

onEndReached(event) {

    if(!onEndReachedActive) return;

    if(this.state.loadingMore || this.state.isLoadingTop)return;
    isLoadingMore = true;
    var posts = this.state.posts;
    server.getStream(posts[posts.length-1].m._id, '', 15)
        .then(res => {
            console.log('received posts');
            posts = posts.concat(res);
            lastPostId = posts[posts.length-1].m._id;
            this.setState({
                dataSource: this.ds.cloneWithRows(posts),
                posts
            }, ()=>isLoadingMore = false);
        })
}

renderHeader() {
    return (
        <View style={styles.header}>
            <Text style={styles.headerText}>Header</Text>
        </View> 
    )
}

renderRow(post) {

    if(post === 'loader') {
        return (
            <ProgressBarAndroid 
                styleAttr="Large" 
                style={styles.spinnerBottom}/>
        )
    }

    let hasLoader = post.m._id === lastPostId;

    let loader = hasLoader ? 
        <ProgressBarAndroid 
            styleAttr="Large" 
            style={styles.spinnerBottom}/> : null;

    return (
        <View>
            <Post 
                post={post}/>
            {loader}
        </View> 
    )
}

render() {


    return (
                <ListView
                    style={styles.mainContainer}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow.bind(this)}
                    onEndReached={this.onEndReached.bind(this)}
                    onEndReachedThreshold={1}
                    pageSize={15} />
    );
}
}

问题在于,每当我追加(或添加)新数据时,rowHasChanged的{​​{1}}方法都不会触发。它只是重新渲染每一行,即使没有任何变化(新数据除外)。 知道为什么绕过这个方法吗?

3 个答案:

答案 0 :(得分:4)

这对我有用,希望这会有所帮助。我创建了一个新的dataSource,并在状态更改时为其分配了更新的数据,如下所示:`

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

  this.setState({ dataSource : dataSource.cloneWithRows(posts) });

现在,已分配新数据并正确呈现视图。请注意,现在分配的posts数组包含更新的数据。仍然在想,如果它是最好的方式,但它的确有效!

答案 1 :(得分:1)

我同意 似乎 ,因为你应该始终使用之前状态的dataSource。

然而,当我以这种方式设置状态时,会为所有行调用 rowHasChanged ,但是, rowHasChanged 始终返回 false 并且不会呈现任何行? ??为什么呢?

  // This is callback handler that the ListView DetailView will 
  // call when a ListView item is edited
  onChange(waypoint: Object){
    console.log('Callback: rowNumber= ', waypoint.rowNumber);
    console.log('        length(m)= ', waypoint.distance.meters);

    var itemListChanged = this.state.itemList;
    itemListChanged[waypoint.rowNumber-1] = waypoint;
    this.setState({
            dataSource: this.state.dataSource.cloneWithRows(itemListChanged),
    });
  },

如果我以这种方式设置状态,则无条件地调用所有行的 renderRow ,而不调用 rowHasChanged 。哪个是对的?

this.setState({
  dataSource: ds.cloneWithRows(itemListChanged),
});

ListView,datasource和react-native是来自C#/ C / C ++的艰难学习曲线。

答案 2 :(得分:0)

对于仍然遇到 rowHasChanged 问题但仍在返回 false 的人,以下代码段可能会有所帮助

数据源像往常一样初始化:

let ds = new ListView.DataSource ({

  rowHasChanged: (a, b) => {
    const changed = (a !== b)
    return changed
  }

})

this.data = []

this.state = {
  listDataSource: ds.cloneWithRows(this.data)
}

这是更新行的功能

updateRow = (row, rowId, sectionId) => {

  // make a shallow clone from the stored data array
  let blob = this.data.concat()

  // modify the row, since we are using the triple equal operator, we need to make sure we are giving it a new object (new ref)
  blob[rowId] = Object.assign({}, blob[rowId], {label: blob[rowId].label + '..cape..deh'})

  // tell react to update the source
  this.setState({
    listDataSource: this.state.listDataSource.cloneWithRows(blob)
  }, () => {
    // we need to update our data storage here! after the state is changed
    this.data = blob
  })

}