反应功能组件懒负荷实现

发布于 2025-01-25 13:07:22 字数 1113 浏览 5 评论 0原文

我们有一个简单的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文