通过React和JavaScript应用无限滚动

时间:2018-08-22 18:58:12

标签: javascript html reactjs material-ui

我正在尝试向页面添加无限滚动。每当用户向下滚动页面时,它将调用jSon,它将更新负责显示消息的数组并因此加载新消息。

但是,如果我到达页面的底部,则如果我向上滚动或向下滚动而不是按照我的预期进行操作,它将调用新消息。

没有显示错误消息,但我不确定为什么会发生这种情况。

代码基于我在这里link所找到的内容,下面的代码就是我现在所拥有的。

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

    this.state = {
      messagesList: [],
      messageCount: 0,
      totalMessages: 0,
    };
  }
  isBottom = el => el.getBoundingClientRect().bottom <= window.innerHeight;

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

  trackScrolling = () => {
    const wrappedElement = document.getElementById("header");
// The if statement bellow checks if the i am at the bottom of the page and if i have more messages to load, the second information comes in the json

    if (this.isBottom(wrappedElement) != null && this.state.messageCount <= this.state.totalMessages) {
      fetchAllMessages(10, this.state.messageCount)
        .then(({ response }) => {
          this.setState({
            messagesList: this.state.messagesList.concat(response.messages.content),
            messageCount: this.state.messageCount + 1,

          });
        })
        .catch(() => null);
      document.removeEventListener('scroll', this.trackScrolling);
    } 
  };

  componentWillMount() {
    fetchAllMessage(10, this.state.messageCount)
      .then(({ response }) => {
        this.setState({
          messageList: response.message.content,
          totalMessage: response.message.totalMessage,
          messageCount: this.state.messageCount + 1,
        });
      })
      .catch(() => null);
  }

  render() {
    return (
      <div>
// Adds the event listener again
        {document.addEventListener('scroll', this.trackScrolling)}
        <Canvas >

          <Title >Messages</Title>

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

            <Card id={"header"}>
              <CardContent>
                <div>
                  <div className={`icon ${MessageType[i.type].class}`} /> // adds an image
                </div>
                <div className="cardText" >
                  <Markdown>
                    {`${i.message} ${i.date != null ? ` on : ${i.date}` : ''}`}   
                  </Markdown>
                </div>
              </CardContent>
            </Card>
              ))}
        </Canvas>

      </div>

    );
  }
}

export default Messages;

我相信这可能与window.innerHeight或我重置滚动侦听器的事实有关,但我不确定。

0 个答案:

没有答案