反应功能组件懒负荷实现
我们有一个简单的React应用程序,其中父组件(ShopItem)在循环中呈现多个儿童组件(评论)。
const ShopItem = ({ item }) => {
const [comments, setComments] = useState(item.comments)
return (
<div>
<div className="item_title">
item.title
</div>
<div className="item_comments">
{comments.map((comment) => {
return (
<CommentCard
commentId={commentId}
/>
)
})}
</div>
</div>
)
}
然后,注释卡组件在内部调用API以获取注释信息,然后在屏幕上渲染。这是我们在ShopItem Prop中收到的物品的结构,
{
title: "Bucket"
price: 90
comments: [
8993,
8992,
8991,
8990,
..
..
..
]
}
我们希望将懒惰加载用于评论部分。例如,在启动时,应仅渲染前5个评论卡,并且当用户开始滚动时,应渲染下5个评论卡,依此类推。由于我们已经有一个在项目上发布的所有注释的列表(以数组的形式),因此我们不需要从服务器中获取评论ID,因此我们只需要管理已经收到的作为道具的列表即可。
我们试图使用React。懒惰和反应。悬浮,但这些并不能满足我们的要求。我不是在寻找一个功能齐全的解决方案,我在这里寻找一种方法。
We have a simple React application where the parent component (ShopItem) renders multiple child components (CommentCard) in a loop.
const ShopItem = ({ item }) => {
const [comments, setComments] = useState(item.comments)
return (
<div>
<div className="item_title">
item.title
</div>
<div className="item_comments">
{comments.map((comment) => {
return (
<CommentCard
commentId={commentId}
/>
)
})}
</div>
</div>
)
}
CommentCard component then internally calls API to fetch comment information and then render it on screen. Here is the structure of the item we receive in ShopItem props
{
title: "Bucket"
price: 90
comments: [
8993,
8992,
8991,
8990,
..
..
..
]
}
We want to apply lazy loading for the Comment section. For example, in starting it should render the first 5 CommentCards only and when the user starts scrolling it should render the next five and so on. As we already have a list of all comments posted on items (in form of the array), we do not need to fetch comment ids from the server, we just need to manage the list we already received as props.
We tried to use React.lazy and React.suspense but those are not fulfilling our requirements. I am not looking for a fully functional solution, I am looking for an approach here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论