如何创建一个钩子来响应事件以加载更多数据?

我正在尝试创建一个功能,如果用户点击一个LOAD MORE按钮,它会返回更多数据。


我已经完成了一些代码,但每次我点击LOAD MORE按钮时,它都会删除前 12 个项目并设置新的 12 个项目,但我不想那样,我想保留 12 个旧项目,这只是一个常规加载更多功能。


const Comp = ({ data }) => {

  const postsPerPage = 12

  const [postsToShow, setPostsToShow] = useState([])

  const [next, setNext] = useState(postsPerPage)


  let arrayForHoldingPosts = []


  const loopWithSlice = (start, end) => {

    const slicedPosts = data.products.slice(start, end)

    arrayForHoldingPosts = [...arrayForHoldingPosts, ...slicedPosts]

    setPostsToShow(arrayForHoldingPosts)

  }


  useEffect(() => {

    loopWithSlice(0, postsPerPage)

  }, [])


  const handleShowMorePosts = () => {

    loopWithSlice(next, next + postsPerPage)

    setNext(next + postsPerPage)

  }


  return (

    <div>

      {postsToShow.map(p => <div>...</div>)}

      <button onClick={handleShowMorePosts}>Load more</button>

    </div>

  )

}

除此之外,我需要将它变成一个钩子,我将在整个应用程序中使用它。


我错过了什么?


有任何想法吗?


慕妹3146593
浏览 92回答 2
2回答

潇潇雨雨

您不需要数组arrayForHoldingPosts ,只需使用 setPostsToShow( [...postsToShow, ...slicedPosts]);arrayForHoldingPosts每次渲染后都变成空数组,因此旧数据丢失。钩子示例const useLoadMore = (data, postsPerPage = 2) => {&nbsp; const [postsToShow, setPostsToShow] = useState([]);&nbsp; const [next, setNext] = useState(postsPerPage);&nbsp; const loopWithSlice = (start, end) => {&nbsp; &nbsp; const slicedPosts = data.slice(start, end);&nbsp; &nbsp; setPostsToShow( [...postsToShow, ...slicedPosts]);&nbsp; };&nbsp; useEffect(() => {&nbsp; &nbsp; loopWithSlice(0, postsPerPage);&nbsp; }, []);&nbsp; const handleShowMorePosts = () => {&nbsp; &nbsp; loopWithSlice(next, next + postsPerPage);&nbsp; &nbsp; setNext(next + postsPerPage);&nbsp; };&nbsp; return { handleShowMorePosts, postsToShow }}const App = ({data}) => {&nbsp; const {handleShowMorePosts, postsToShow } = useLoadMore(data)&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {postsToShow.map((p) => (&nbsp; &nbsp; &nbsp; &nbsp; <div>...</div>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; <button onClick={handleShowMorePosts}>Load more</button>&nbsp; &nbsp; </div>&nbsp; );};

四季花海

这里有一个问题,strong textlet arrayForHoldingPosts = []这将在每个渲染器上分配空数组。setPostsToShow 应该是,const loopWithSlice = (start, end) => {const slicedPosts = data.products.slice(start, end)setPostsToShow(posts=>([...posts, ...slicedPosts]))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript