【发布时间】:2021-03-02 23:40:54
【问题描述】:
我目前正在尝试使用 useState 挂钩实现无限滚动分页功能,以获取接下来的 30 个项目(对象)。下面看到的useEffect 会获取前 30 个项目并将其设置为网页上的当前状态。但是,当我滚动到底部后,当我的 fetchMoreListItems() 被调用以拉下一组 30 个时,它不会将其附加到前 30 个项目中,而是在我的 fetchMoreListItems() 中刷新页面和 setItems函数完全用下一个对象替换以前的对象。我正在尝试通过附加更新的状态来找到一种连接先前状态的方法。有没有办法解决这个问题?我的尝试如下所示:
const [items, setItems] = useState<Resource<Activities>[]>();
const [isFetching, setIsFetching] = useState(false);
useEffect(() => {
if (!props.resource) return;
props.resource
.follow('activities-collection').followAll('item')
.then(resources => {
// this sets the first 30 objects to be displayed
setItems(resources);
})
.catch(err => console.error('Error fetching resources: ' + err));
}, [activityResource]);
function fetchMoreListItems() {
setTimeout(() => {
if (!props.resource) return;
props.resource
.follow('activities-collection').follow('next').followAll('item')
.then(resources => {
// I would like to append these new objects instead of replacing old ones
setItems(resources);
})
.catch(err => console.error('Error fetching resources: ' + err));
setIsFetching(false);
}, 1000);
}
【问题讨论】:
标签: reactjs typescript object