我使用React Native ListView组件,但我不知道它为什么会自动运行onEndReached函数,尽管滚动仍在顶部。
我希望滚动转到设备底部,然后运行onEndReached函数。但是在下面的代码中,当我转到页面时,它将连续运行onEndReached函数。
以下是我的组件
class MovieList extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: [],
loaded: false,
count: 10,
start: 0,
total: 0
};
this.dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
});
this.REQUEST_URL = 'https://api.douban.com/v2/movie/top250';
this.fetchData();
}
requestURL(
url = this.REQUEST_URL,
count = this.state.count,
start = this.state.start
) {
return (
`${url}?count=${count}&start=${start}`
);
}
fetchData() {
fetch(this.requestURL())
.then(response => response.json())
.then(responseData => {
let newStart = responseData.start + responseData.count;
this.setState({
movies: responseData.subjects,
loaded: true,
total: responseData.total,
start: newStart,
});
})
.done();
}
renderMovieList(movie, sectionId, rowId, highlightRow) {
return (
<View>
<View style={styles.item}>
<View style={styles.itemImage}>
<Image
source={{uri: movie.images.large}}
style={styles.image}
/>
</View>
<View style={styles.itemContent}>
<Text style={styles.itemHeader}>{movie.title}</Text>
<Text style={styles.itemMeta}>
{movie.original_title} ( {movie.year} )
</Text>
<Text style={styles.redText}>
{movie.rating.average}
</Text>
</View>
</View>
</View>
);
}
loadMore() {
fetch(this.requestURL())
.then(response => response.json())
.then(responseData => {
let newStart = responseData.start + responseData.count;
this.setState({
movies: [...this.state.movies, ...responseData.subjects],
start: newStart
});
})
.done();
}
onEndReached() {
console.log(
`reached start:${this.state.start}, total:${this.state.total}`
);
if (this.state.total > this.state.start) {
this.loadMore();
}
}
renderFooter() {
if (this.state.total > this.state.start) {
return (
<View
style={{
marginVertical: 20,
paddingBottom: 50,
alignSelf: 'center'
}}
>
<ActivityIndicatorIOS />
</View>
);
} else {
return (
<View
style={{
marginVertical: 20,
paddingBottom: 50,
alignSelf: 'center'
}}
>
<Text
style={{
color: 'rgba(0, 0, 0, 0.3)'
}}
>no more load :D</Text>
</View>
);
}
}
render() {
if (!this.state.loaded) {
return (
<View style={{backgroundColor: '#eae7ff', flex: 1}}>
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicatorIOS
size="large"
color="#6435c9"
/>
</View>
</View>
);
}
return (
<View style={{backgroundColor: '#eae7ff', flex: 1}}>
<ListView
renderFooter={this.renderFooter.bind(this)}
pageSize={this.state.count}
onEndReached={this.onEndReached.bind(this)}
initialListSize={this.state.count}
dataSource={this.dataSource.cloneWithRows(this.state.movies)}
renderRow={this.renderMovieList.bind(this)}
/>
</View>
);
}
}
感谢您的帮助!
答案 0 :(得分:2)
我不知道为什么,但我从其他方面得到了一些帮助。
我删除了ScrollView组件,因为有人告诉我ListView包含ScrollView,然后将style={{flex:1}}
提供给ListView组件,它可以工作。