当用户到达页面底部时发出警报

时间:2018-08-20 21:17:04

标签: javascript reactjs react-redux material-ui infinite-scroll

我试图实现无限滚动以加载通过我映射的Json接收到的消息,并且当用户到达页面底部时,它将加载更多内容。 我已经尝试了一些发现的代码,但是它们都不起作用,或者只是给了我无法纠正的错误。我不太确定该怎么办。

现在,我试图仅在console.log上显示我已到达页面底部,但出现以下错误:

Uncaught TypeError: Cannot read property 'getBoundingClientRect' of null
    at ProxyComponent.Notifications._this.isBottom
    at HTMLDocument.Notifications._this.trackScrolling

这是我现在拥有的代码:

class Messages extends React.Component {
      constructor(props) {
        super(props);

    this.state = {
      messageList: [],
    };
  }

  isBottom = el => el.getBoundingClientRect().bottom <= window.innerHeight

  componentDidMount() {
    document.addEventListener('scroll', this.trackScrolling);
  }

  trackScrolling = () => {
    const wrappedElement = document.getElementById('header');
    if (this.isBottom(wrappedElement)) {
      alert('header bottom reached');
      document.removeEventListener('scroll', this.trackScrolling);
    }
  };
  componentWillMount() {
    fetchAllMessages(30, 0)
      .then(({ response }) => {
        this.setState({
          messageList: response.messages.content,
        });
      })
      .catch(() => null);
  }

  render() {
    return (
      <div>

        <Canvas >
          <Title >Messages</Title>

          {this.state.messagesList.map(i => (

            <Card key={i.id}>
              <CardContent className="cardContent">
                <div className="icon-container-message">
                  <div className={`icon ${MessageType[i.type].class}`} />
                </div>
                <div className="cardText" >
                  <Markdown>
                    {i.message}
                  </Markdown>
                  <InsertInvitation />{i.date}
                </div>
              </CardContent>
            </Card>
        ))}
        </Canvas>
      </div>

    );
  }
}

export default Messages;

我正在尝试实施此处找到的解决方案:Detecting when user scrolls to bottom of div with React js

0 个答案:

没有答案