如何避免此消息警告“最大更新深度超过...”在NextJS上

发布于 2025-02-10 16:09:58 字数 1803 浏览 0 评论 0原文

在NextJS上,我不明白使用效率如何工作。我需要做的事情,以停止接收此警告消息 “超过最大更新深度”:

Code Bellow是页面,调用组件ListContainer,此页面将项目添加到容器中。

页面JSX:

    import { useState } from "react";
import AppLayout from "../components/AppLayout";
import ListContainer from "../components/ListContainer";

export default function componentCreator(){


  
    const [item,setItem] = useState([])   

/* add item to container */
    function addItem(){

        let newItem = item
        newItem.push({
            produto: 'Skol 350ml',
            preco: '1200,00',
            quantidade: 'cx c/ 15 unidades'
        })
        setItem(newItem)

    }

    return (
        <AppLayout>
            <ListContainer items={item} setItems={setItem}/>
            <div className="productcardbuttonshow" onClick={() => addItem()}>ADICIONAR</div>
        </AppLayout>
    )
}

呼吸处理项目的组件,删除或添加。但是它有效,但是在控制台上触发有关更新的警告消息。 组件ListContainer.jsx:

import { useState,useEffect } from "react";
export default function ListContainer(props){

    const [html,setHTML] = useState(null)
    const [item,setItem] = useState(props.items)
  
/* refresh html container */
    useEffect(() => {
        const itemHTML = item.map((itemmap,id) => {
            return (
                <div id={id} onClick={() => delItem(id)} className="itemProposta">
                    {itemmap.produto} - {itemmap.quantidade} - R$ {itemmap.preco}
                </div>
            )
        })
        setHTML(itemHTML)
    })

/* remove item from container */
    function delItem(id){
        let itemlist = props.items
        itemlist.splice(id,1)
        props.setItems(itemlist)
    }

    return (
        <>
        {html}
        </>
    )
}

on NextJs i not understand, how useEffect work. What i need to do, to stop of receiving this warning message
"Maximum update depth exceeded":

The Code bellow is the page, that call a component ListContainer, this page add a item to container.

The page JSX:

    import { useState } from "react";
import AppLayout from "../components/AppLayout";
import ListContainer from "../components/ListContainer";

export default function componentCreator(){


  
    const [item,setItem] = useState([])   

/* add item to container */
    function addItem(){

        let newItem = item
        newItem.push({
            produto: 'Skol 350ml',
            preco: '1200,00',
            quantidade: 'cx c/ 15 unidades'
        })
        setItem(newItem)

    }

    return (
        <AppLayout>
            <ListContainer items={item} setItems={setItem}/>
            <div className="productcardbuttonshow" onClick={() => addItem()}>ADICIONAR</div>
        </AppLayout>
    )
}

Bellow the component that handle the items, remove or add. But it works, but on console trigger warning messages about update.
Component ListContainer.jsx:

import { useState,useEffect } from "react";
export default function ListContainer(props){

    const [html,setHTML] = useState(null)
    const [item,setItem] = useState(props.items)
  
/* refresh html container */
    useEffect(() => {
        const itemHTML = item.map((itemmap,id) => {
            return (
                <div id={id} onClick={() => delItem(id)} className="itemProposta">
                    {itemmap.produto} - {itemmap.quantidade} - R$ {itemmap.preco}
                </div>
            )
        })
        setHTML(itemHTML)
    })

/* remove item from container */
    function delItem(id){
        let itemlist = props.items
        itemlist.splice(id,1)
        props.setItems(itemlist)
    }

    return (
        <>
        {html}
        </>
    )
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美人骨 2025-02-17 16:09:58

您正在进入无限的渲染循环。此代码负责:

useEffect(() => {
        const itemHTML = item.map((itemmap,id) => {
            return (
                <div id={id} onClick={() => delItem(id)} className="itemProposta">
                    {itemmap.produto} - {itemmap.quantidade} - R$ {itemmap.preco}
                </div>
            )
        })
        setHTML(itemHTML)
    })

此回调使用效果在每个渲染后都会运行,因为没有依赖项数组。这意味着在每次渲染后,sethtml(itemhtml)被调用。即使数组的组成对象itemHtml是相同的,也会创建数组的新引用。由于.map()返回数组的新引用,因此创建了一个新的引用。尽管渲染和更新正常,但正在发生无限渲染。

考虑添加dependency array to useEffect.例如:

useEffect(() => {
/* function body */
},[props.items]);

现在使用回调仅在props.items参考更改时运行。

旁注(与您的问题无关)
在以下代码中,

  function addItem(){

        let newItem = item
        newItem.push({
            produto: 'Skol 350ml',
            preco: '1200,00',
            quantidade: 'cx c/ 15 unidades'
        })
        setItem(newItem)

    }

您应该执行let newitem = [... item],否则您不会创建iteg> item array和setItem(newitem)的新参考)在这种情况下基本上没有用。

You are getting into an infinite loops of renders. This code is responsible:

useEffect(() => {
        const itemHTML = item.map((itemmap,id) => {
            return (
                <div id={id} onClick={() => delItem(id)} className="itemProposta">
                    {itemmap.produto} - {itemmap.quantidade} - R$ {itemmap.preco}
                </div>
            )
        })
        setHTML(itemHTML)
    })

This callback inside useEffect will run after every render, because there is no dependency array. That means after every render, setHTML(itemHTML) is called. And even if the constituent objects of the array itemHTML are same, a new reference of the array is created. A new reference is created because .map() returns a new reference of the array. And although render and update works correctly, infinite rendering is happening.

Consider adding a dependency array to useEffect. For example:

useEffect(() => {
/* function body */
},[props.items]);

Now useEffect callback only runs if props.items reference changes.

Side note (unrelated to your question):
In the below code,

  function addItem(){

        let newItem = item
        newItem.push({
            produto: 'Skol 350ml',
            preco: '1200,00',
            quantidade: 'cx c/ 15 unidades'
        })
        setItem(newItem)

    }

You should do let newItem = [...item], otherwise you are not creating a new reference of item array and setItem(newItem) is basically useless in that case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文