2 回答
TA贡献1833条经验 获得超4个赞
您不需要数组arrayForHoldingPosts ,只需使用 setPostsToShow( [...postsToShow, ...slicedPosts]);
arrayForHoldingPosts每次渲染后都变成空数组,因此旧数据丢失。
钩子示例
const useLoadMore = (data, postsPerPage = 2) => {
const [postsToShow, setPostsToShow] = useState([]);
const [next, setNext] = useState(postsPerPage);
const loopWithSlice = (start, end) => {
const slicedPosts = data.slice(start, end);
setPostsToShow( [...postsToShow, ...slicedPosts]);
};
useEffect(() => {
loopWithSlice(0, postsPerPage);
}, []);
const handleShowMorePosts = () => {
loopWithSlice(next, next + postsPerPage);
setNext(next + postsPerPage);
};
return { handleShowMorePosts, postsToShow }
}
const App = ({data}) => {
const {handleShowMorePosts, postsToShow } = useLoadMore(data)
return (
<div>
{postsToShow.map((p) => (
<div>...</div>
))}
<button onClick={handleShowMorePosts}>Load more</button>
</div>
);
};
TA贡献1811条经验 获得超5个赞
这里有一个问题,
strong textlet arrayForHoldingPosts = []
这将在每个渲染器上分配空数组。
setPostsToShow 应该是,
const loopWithSlice = (start, end) => {
const slicedPosts = data.products.slice(start, end)
setPostsToShow(posts=>([...posts, ...slicedPosts]))
}
添加回答
举报