反应警告超过最大更新深度 [英] React warning Maximum update depth exceeded

查看:33
本文介绍了反应警告超过最大更新深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是这个问题的后续问题,最接近我的问题:

This is a follow up question to this question which is the nearest to my issue:

useEffect 中的无限循环

我正在创建一个小型 React.js 应用程序来研究该库.我收到此警告:

I am creating a small React.js app to study the library. I'm getting this warning:

已超出最大更新深度.当组件在 useEffect 中调用 setState 时,可能会发生这种情况,但 useEffect 要么没有依赖项数组,要么每次渲染时依赖项之一发生变化.

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

我得到了一个功能组件,里面有这个代码:

I got a functional component, in which there is this code:

const propertiesMap2 = new Map([  //There is also propertiesMap1 which has the same structure
["TITLE4",
    {
        propertyValues: {
            myProperty10 : "myVal1",
            myProperty11 : "myVal2",
            myProperty12 : "myVal3",                                                            
        },
        isOpen: true
    }
],
["TITLE5",
    {
        propertyValues: {
            myProperty13 : "myVal4",
            myProperty14 : "myVal5",
            myProperty15 : "myVal6",                                                             
        },
        isOpen: true
    }
],
["TITLE6",
    {
        propertyValues:{
            myProperty16 : "myVal7",
            myProperty17 : "myVal8",
            myProperty18 : "myVal9",
        },
        isOpen: true
    }                                                        
]
]);

const [properties, setPropertiesMapFunc] = useState(new Map());
useEffect(()=>
{
    let mapNum = Number(props.match.params.id);
    setPropertiesMapFunc(mapNum === 1 ?propertiesMap1 : propertiesMap2);
}, [properties]);

每次都会选择正确的属性映射,但就像我说的那样,我收到了这个错误.为什么我得到它,如果 propertiesMap 是不变的,没有任何变化,并且 properties 作为参数传递给 setEffect,所以我认为它只会在某些内容发生变化时重新渲染..

The correct properties map is chosen each time, but like I said I get this error. Why do I get it, if the propertiesMap is constant without anything changing, and properties was passed as a parameter to setEffect, so I thought it would only re render when something there changes..

推荐答案

因为您是在组件函数内部创建地图对象,所以它们将在每次渲染时重新创建.因此,您的效果会将新地图设置为新状态,这反过来又会触发另一次重新渲染,您的效果会再次被调用,从而导致无限更新循环.

Because you are creating the map objects inside of your component function they will be recreated on every render. Because of that your effect will set a new map as the new state which will in turn trigger another re-render and your effect being called again which leads to an infinite update loop.

您可以将地图对象的定义移到组件之外来解决此问题.

You can move the definition of your map objects outside of your component to fix this.

这篇关于反应警告超过最大更新深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆