无限滚动-滚动到底部确实没有任何作用

时间:2019-05-07 17:24:27

标签: reactjs react-redux react-hooks

我从redux HOC制作了具有数组的组件。接下来,我使用本教程构建了无限滚动: https://upmostly.com/tutorials/build-an-infinite-scroll-component-in-react-using-react-hooks/

它从数组中加载20个项目并进行渲染。很好 接下来,当我滚动到页面底部时,它应该呈现下20个项目。它不起作用。 在Google devtool中,我检查了handleScroll函数是否未更改isFetching状态。

这是我第三次尝试无限滚动。我尝试使用外部库在不使用钩子的情况下执行此操作,但是每次滚动到页面底部都不会执行任何操作。

空投列表组件

import React, { useEffect, useState } from "react";
import AirdropBlock from "./AirdropBlock/AirdropBlock";
import { Paper } from "@material-ui/core";
import { withStyles } from "@material-ui/core/styles";

const styles = {
  paper: {
    display: "flex",
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-evenly"
  }
};

const AirdropPanel = props => {
  const { classes, filteredAndSortedAirdrops } = props;
  const [airdropList, setAirdropList] = useState(
    filteredAndSortedAirdrops.slice(0, 20)
  );
  const [isFetching, setIsFetching] = useState(false);

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  useEffect(() => {
    if (!isFetching) return;
    fetchMoreAirdrops();
  }, [isFetching]);

  function handleScroll() {
    if (
      window.innerHeight + document.documentElement.scrollTop !==
        document.documentElement.offsetHeight ||
      isFetching
    )
      return;
    setIsFetching(true);
  }

  function fetchMoreAirdrops() {
    setAirdropList(prevState => [
      ...prevState,
      ...filteredAndSortedAirdrops.slice(
        prevState.length,
        prevState.length + 20
      )
    ]);
    setIsFetching(false);
  }

  const airdropBlocks = airdropList.map(e => {
    return (
      <AirdropBlock
        key={e.id}
        title={e.title}
        value={e.value}
        status={e.status}
        logo={e.logo}
        id={e.id}
      />
    );
  });

  return (
    <Paper className={classes.paper} data-testid="airdropPanel">
      {airdropBlocks}
      {isFetching && "Fetching more airdrops..."}
    </Paper>
  );
};

export default withStyles(styles)(AirdropPanel);

为空投列表组件提供数组的HOC

import AirdropPanel from "./AirdropPanel";
import { connect } from "react-redux";
import { onlyNotActiveFiltersNames } from "./helpers/onlyNotActiveFiltersNames";
import { toFilterAirdrops } from "./helpers/toFilterAirdrops";

const mapStateToProps = state => {
  const nonActiveFilters = onlyNotActiveFiltersNames(state.filters);
  const filteredAirdrops = toFilterAirdrops(state.airdrops, nonActiveFilters);
  const filteredAndSortedAirdrops = filteredAirdrops.sort((a, b) => {
    return b.addDate - a.addDate;
  });
  return {
    filteredAndSortedAirdrops
  };
};

const mapDispatchToProps = null;

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(AirdropPanel);

我希望在我的代码中发现错误或逻辑错误。如果它需要更多代码或需要解释,我会做。

0 个答案:

没有答案