gpt4 book ai didi

javascript - onEndReached 导致 ListView 上显示多个项目

转载 作者:行者123 更新时间:2023-11-30 20:35:02 25 4
gpt4 key购买 nike

我最终在我的 ListView 中有多个项目重复,因为出于某种原因多次使用相同的参数“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!

谁知道我怎样才能避免这样的事情?

最佳答案

您必须将 onEndReachedThresholdonEndReached 结合使用,以防止发生奇怪的行为

docs 中所述

onEndReached : Called once when the scroll position gets within onEndReachedThreshold of the rendered content.

因此您可以将值设置为 onEndReachedThreshold={0.5}

0.5 将在内容末尾在列表可见长度的一半以内时触发 onEndReached

要删除重复项,您需要将它们合并为 concat组合两个具有或不具有唯一值的数组。

因此像往常一样,您可以使用 es6 spread operator

例子

let arr1 = [1, 2, 3];
let arr2 = [3, 5, 6];

let deDupeIt = (...arrs) => [ ...new Set( [].concat(...arrs) ) ];

let dedupedArrays = deDupeIt(arr1, arr2)
console.log(dedupedArrays)

在您的情况下,在某处定义函数并将其称为

this.setState({
categories: deDupeIt(this.state.categories, response.data.data),
isLoading: false,
});

注意:

如果您使用代码片段的第二部分应该使用 prevState.page + 1 而不是 prevState + 1

关于javascript - onEndReached 导致 ListView 上显示多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49936537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com