简体   繁体   English

useEffect 对象依赖无限循环 - ReactJS

[英]useEffect Object dependency infinite loop - ReactJS

I have a State in Context with Object.我在对象的上下文中有一个状态。 I am running a async function in the useEffect and passing my object state as dependency .我在useEffect中运行async函数并将我的对象状态作为dependency项传递。

I passed the state object as dependency because i want to re-render the component when values of settings object changes.我将状态对象作为依赖项传递,因为我想在settings对象的值更改时重新渲染组件。

But it causes an infinite loop.但它会导致无限循环。

Update:更新:
Let me clear my question more.让我更清楚我的问题。
In my useEffect , I am calling my async function addTextItem() which calls the function finalPrice and it updates the state, but this way it causes infinite loop.在我的useEffect中,我正在调用我的异步函数addTextItem() ,它调用函数finalPrice并更新状态,但是这样会导致无限循环。
On other hand, If i call finalPrice in the useEffect directly instead of calling addTextItem then there is no infinite loop but it is also updating the state, right?另一方面,如果我直接在useEffect中调用finalPrice而不是调用addTextItem则没有无限循环,但它也在更新状态,对吗? then how this could be.那么这怎么可能。 & I need a solution as i have tried everything and now totally stuck. &我需要一个解决方案,因为我已经尝试了所有方法,但现在完全卡住了。

Here is the code:这是代码:

export default function CustomizerState(props) {
    const initialText = "Hello"
    const initialSize = {
        x: REACT_APP_SIZE_X,
        y: REACT_APP_SIZE_Y
    }
    const initialTextItem = {
        id: generateID(),
        text: "Hello",
        font: fonts[0].value,
        size: initialSize,
        color: colors[0],
        backplate: "cut-sharp",
        uvPrint: false,
        quantity: 1,
        neonPrice: 0,
        backplatePrice: 0,
        neonPower: 0,
        totalPrice: 0
    }
    const [settings, setSettings] = useState({
        textItems: [],
        libraryItems: [],
        ownDesigns: [],
        accessories: [
            // My Objects here
        ],
        finalPrice: 0
    })

    const addTextItem = async () => {
        const pathLength = await textToPath(initialText, initialSize.x)
        const { backplatePrice, neonPrice, neonPower, totalPrice } = calculateSvgPrice(pathLength)
        const id = generateID()

        const newItems = [
            ...settings.textItems,
            {...initialTextItem, id, backplatePrice, neonPrice, neonPower, totalPrice}
        ]
        
        finalPrice("textItems", newItems)
    }

    const finalPrice = (itemType = null, items = null) => {
        const textItemsPrice = getTotalPrice()
        const libraryItemsPrice = getTotalPrice("libraryItems")
        const accessoriesPrice = getTotalPrice("accessories", "unitPrice")

        const finalPrice = textItemsPrice + libraryItemsPrice + parseInt(accessoriesPrice)

        if (itemType === null) {
            setSettings((prevState) => (
                {...prevState, finalPrice}
            ))
            return false
        }

        setSettings((prevState) => (
            {...prevState, [itemType]: items, finalPrice}
        ))
    }

    useEffect(() => {
        // It will add first initial form item
        addTextItem()
    }, [JSON.stringify(settings)])

    return (
        <CustomizerContext.Provider value={{settings, addTextItem}}>
            {props.children}
        </CustomizerContext.Provider>
    )
}

在此处输入图像描述

I have google and tried the solutions, but nothing worked for me.我有谷歌并尝试了解决方案,但对我没有任何帮助。 Can someone help me to fix this issue?有人可以帮我解决这个问题吗? I am stuck....我被困住了......

Check the useEffect hook documentation .检查useEffect 挂钩文档 The array passed in the second argument array is the dependency array:第二个参数数组中传递的数组是依赖数组:

useEffect(() => {
    //hook code   
}, []);

The dependency array will make the hook code execute everytime any variable of the array changes.每当数组的任何变量发生变化时,依赖数组都会执行钩子代码。 In your case you are changing the depency item settings in the call itself producing an infinite loop.在您的情况下,您正在更改调用本身中的依赖项settings ,从而产生无限循环。

I forgot that when re-rendering happens, it also runs useEffect obviously and it causes setState again and again.我忘记了当重新渲染发生时,它显然也会运行useEffect并且它会一次又一次地导致setState
I managed to fix this by creating a state named initialItemCount with 0 initial value.我设法通过创建一个名为initialItemCount且初始值为0的状态来解决此问题。 I am checking if that state value is 0 then run addTextItem which will add my initial form item and updates the final price, but if the value 1 then only run the finalPrice function.我正在检查该状态值是否为 0,然后运行addTextItem它将添加我的初始表单项并更新最终价格,但如果值为 1,则仅运行finalPrice函数。

const [initialItemCount, setInitialItemCount] = useState(0)
useEffect(() => {
    if (initialItemCount === 0) {
        addTextItem()
        setInitialItemCount(1)
    }
    
    if (initialItemCount === 1) {
        finalPrice()
    }
}, [JSON.stringify(settings)])

Finally, inner peace.最后,内心平静。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReactJS - UseEffect 与上下文一起使用 API 在依赖数组未保持为空时导致无限循环 - ReactJS - UseEffect used with context API is causing infinite loop when dependency array is not kept empty reactjs 使用 useState 和 useEffect 避免无限循环 - reactjs Avoid Infinite loop using the useState and useEffect 无法打破 Reactjs useEffect 无限循环 - Cant break Reactjs useEffect infinite loop 在 useEffect 钩子中添加依赖会导致无限循环 - Adding dependency in useEffect hook causes infinite loop 具有空依赖数组的 useEffect 无限循环 - Infinite loop of useEffect with empty dependency array 如何在 useEffect 中包含缺少的依赖项但防止 function 的无限循环执行? - How to include missing dependency in useEffect but prevent infinite loop execution of function? React Hooks useEffect,添加依赖触发器无限循环 - React Hooks useEffect, adding dependency triggers infinite loop React redux 减速器作为 UseEffect 依赖导致无限循环 - React redux reducer as UseEffect dependency causes infinite loop 当数组作为依赖项传递时,React 中的 useEffect 在无限循环中运行 - useEffect in React runs in an infinite loop, when an array is passed as a dependency useEffect 与 function 一起更新 state 作为依赖导致无限循环 - useEffect with function that update the state as dependency leads to infinite loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM