用rxjs实现无限滚动

时间:2019-07-08 08:39:21

标签: javascript rxjs

用rxjs实现无限滚动时遇到麻烦

我尝试了以下代码段

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
}

如何在没有全局变量'lastid'的情况下将lastid传递给每个请求?

谢谢

1 个答案:

答案 0 :(得分:0)

还没有测试代码,但是您可以尝试下面的代码片段。这里的技术是从一个包含您的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))