【发布时间】:2018-04-20 07:41:06
【问题描述】:
我最终在我的列表视图上重复了多个项目,因为由于某种原因多次使用相同的参数 'page=1' 调用 api,而且 onEndReached 在我不滚动的情况下自行触发。
我尝试过这样的事情:
componentDidMount() {
this.fetchCategories();
}
fetchCategories() {
this.setState({isLoading: true});
categoryApi.getOne(this.state.page).then(response => {
if (response.data) {
this.setState({
categories: this.state.categories.concat(response.data.data),
isLoading: false,
});
} else {
this.setState({isLoading: false});
Alert.alert(
'Something wrong happened!',
'My Alert Msg',
[],
{cancelable: true}
)
}
}); }
this.state = {
isLoading: false,
categories: [],
page: 1,
};
showMore = () => {
this.setState({page: this.state.page + 1});
this.fetchCategories();
};
<FlatList
data={this.state.categories}
extraData={this.state}
renderItem={(rowData) => <CategoryItem navigate={navigate} item={rowData}/>}
onEndReached={this.showMore}
keyExtractor={(item, index) => index}
/>
我尝试了什么: 将 showMore 更改为:
showMore = () => {
// console.log("End reached.");
this.setState(prevState =>({
page: prevState + 1
}), () => {
this.fetchCategories();
});
};
我仍然可以看到 page=1 的重复项,api 仍然被多次调用参数 page = 1!
有人知道我怎样才能避免这种事情吗?
【问题讨论】:
-
你试过
onEndReachedThreshold={0.5}吗? -
@PritishVaidya 看起来 onEndReachedThreshold={0.5} 解决了自行触发的问题,但是当我尝试滚动时,我仍然可以在列表中看到重复的项目,似乎我的 api 在页面状态之前被调用变了,所以基本上页面值没有及时递增!
-
您正在尝试在
this.state.categories.concat(response.data.data)此处合并数据,因此它将其添加到数组中,而不是您应该合并数组。 -
所以你说我应该使用 .merge() 而不是 .concat() ?
标签: javascript reactjs react-native ecmascript-6 react-native-android