简体   繁体   English

用rxjs实现无限滚动

[英]implement infinite scroll with rxjs

I'm having trouble when implement infinite scroll with rxjs 使用rxjs实现无限滚动时遇到麻烦

I have tried following snippet 我已经尝试了以下片段

var lastid = null
fromEvent(window, 'scroll')
  .pipe(
    filter(() => isAtPageBottom()),
    exhaustMap(() => from(this.getList(lastid))),
    takeWhile(list => list.length !== 0),
    scan((cur, list) => [...cur, ...list], [])
  )
  .subscribe(list => {
    this.setState({list: list})
  })

async function getList (lastid) {
  const list = await request('/api/list?lastid=' + lastid)
  listid = list[list.length-1].id
  return list
}

How to pass the lastid to each request without the global variable 'lastid'? 如何在没有全局变量“ lastid”的情况下将lastid传递给每个请求?

Thanks 谢谢

haven't test the code but you can try the below code snippet. 尚未测试代码,但是您可以尝试以下代码段。 The technique here is to start off with a state that contains your list and lastId then use expand to keep the stream going and listen for scroll 此处的技术是从一个包含listlastId的状态开始,然后使用expand保持流继续进行并侦听滚动

of({ list: [], lastId: null }).pipe(
    expand((obj) => {
        return fromEvent(window, 'scroll')
            .pipe(
                filter(() => isAtPageBottom()),
                exhaustMap(() => from(this.getList(obj.lastid))),
                map(res => ({ list: obj.list.concat(res), lastId: res[res.length - 1].id }))
            )
    }),
    takeWhile(({ list }) => list.length !== 0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM