【问题标题】:How append to objects by using useState for infinite scrolling pagination?如何使用 useState 附加到对象进行无限滚动分页?
【发布时间】:2021-03-02 23:40:54
【问题描述】:

我目前正在尝试使用 useState 挂钩实现无限滚动分页功能,以获取接下来的 30 个项目(对象)。下面看到的useEffect 会获取前 30 个项目并将其设置为网页上的当前状态。但是,当我滚动到底部后,当我的 fetchMoreListItems() 被调用以拉下一组 30 个时,它不会将其附加到前 30 个项目中,而是在我的 fetchMoreListItems() 中刷新页面和 setItems函数完全用下一个对象替换以前的对象。我正在尝试通过附加更新的状态来找到一种连接先前状态的方法。有没有办法解决这个问题?我的尝试如下所示:

const [items, setItems] = useState<Resource<Activities>[]>();
const [isFetching, setIsFetching] = useState(false);

useEffect(() => {
    if (!props.resource) return;
    props.resource
      .follow('activities-collection').followAll('item')
      .then(resources => {
        // this sets the first 30 objects to be displayed
        setItems(resources);
      })
      .catch(err => console.error('Error fetching resources: ' + err));
  }, [activityResource]);

  function fetchMoreListItems() {
    setTimeout(() => {
      if (!props.resource) return;
      props.resource
        .follow('activities-collection').follow('next').followAll('item')
        .then(resources => {
         // I would like to append these new objects instead of replacing old ones
          setItems(resources);
        })
        .catch(err => console.error('Error fetching resources: ' + err));
      setIsFetching(false);
    }, 1000);
  }

【问题讨论】:

    标签: reactjs typescript object


    【解决方案1】:

    您可以为此使用一个不错的 ES6 功能。

    setItems([...items, ...resources])

    但我也建议不要重建轮子。 React Query 让这个变得非常简单,隐藏了所有的丑陋

    【讨论】:

      【解决方案2】:

      设置两个数组连接的状态怎么样?

      function fetchMoreListItems() {
        setTimeout(() => {
          if (!props.resource) return;
          props.resource
            .follow('activities-collection').follow('next').followAll('item')
            .then(resources => {
               setItems(items.concat(resources));
            })
            .catch(err => console.error('Error fetching resources: ' + err));
          setIsFetching(false);
        }, 1000);
      }
      

      【讨论】:

        猜你喜欢
        • 2016-10-17
        • 2020-04-01
        • 2012-10-05
        • 2016-10-10
        • 1970-01-01
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        • 2020-08-15
        相关资源
        最近更新 更多