[英]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.