redux 和监听滚动事件

redux and listening to scroll events

构建一个性能敏感的 Redux 应用程序,需要在整个用户会话中监听 scroll/mouse 事件。

简单的英语实现是:

"When component A is in the user's viewport, dispatch FOO action"

据我了解,函数 calculateViewPort + 比较检查需要在存储中对每个滚动事件进行。

这看起来太过分而且很慢(还没有测试过)。

是否还有我尚未考虑的其他实现或方法?

我正在考虑为 Redux 使用 RxJS 之类的东西,但想考虑在引入新库以提高性能和使用我现有的工具包解决它之间进行权衡。

如果有传奇方法,我也更愿意接受。

有一个 InfiniteScroll 组件。你可以参考这个并按照你的方式实现,或者你可以按原样使用。

注意:此组件未使用 redux-saga

最好使用 redux-saga,因为您只需要来自最近 api 调用(最后一次鼠标滚动)的响应,效果为 takeLatest

React Visibility Sensor 在这里可能是个不错的选择。您可以将组件包装在 VisibilitySensor 组件中,并在它位于 window 视口时分派一个动作。

import React from 'react'
import { connect } from 'react-redux'
import VisibilitySensor from 'react-visibility-sensor'

import CUSTOM_ACTION from 'your-actions'

const CustomComponent = (noticeMe, ...children) => {
      const handleChange = (isVisible) => { if (isVisible) { noticeMe(); } }
      return <VisibilitySensor>{children}</VisibilitySensor>
    }
export connect({}, {
   noticeMe: () => dispatch(CUSTOM_ACTION)
})(CustomComponent)