[英]using state from a context provider within my useEffect dependency array causes an infinite loop
I am using the shopify-buy
SDK, which allows me to retrieve the current cart of the user.我正在使用
shopify-buy
SDK,它允许我检索用户的当前购物车。 I am trying to store that cart in my CartProvider
which is then used in my Cart
component.我正在尝试将该购物车存储在我的
CartProvider
中,然后在我的Cart
组件中使用它。 The problem is when I retrieve information from the cart it's acting a little slow so my component needs to be updated when the state changes, currently I have the following in my getShopifyCart
function which is located in my CartProvider
.问题是当我从购物车中检索信息时,它的运行速度有点慢,因此当 state 更改时我的组件需要更新,目前我的
getShopifyCart
function 中有以下内容,它位于我的CartProvider
中。
const [cartItems, setCartItems] = useState([])
const getShopifyCart = () => {
return client.checkout
.fetch(currentVendor.cartId)
.then((res) => {
const lineItemsData = res.lineItems.map((item) => {
return {
title: item.title,
quantity: item.quantity,
}
})
setCartItems(lineItemsData)
setLoading(false)
})
.catch((err) => console.log(err))
}
In my Cart
component I have the following useEffect
.在我的
Cart
组件中,我有以下useEffect
。
useEffect(() => {
getShopifyCart()
}, [cartItems])
But this causes an infinite loop, even though the cartItems
state isn't changing.但这会导致无限循环,即使
cartItems
state 没有改变。
You are setting the state cartItems
inside getShopifyCart
which you are calling inside a useEffect
which has cartItems
as a dependency.您正在 getShopifyCart 中设置 state
cartItems
,您在getShopifyCart
中调用它,它具有useEffect
作为依赖cartItems
。 Even though the content of the data has not changed, you are creating a new object, hence its hash has changed as well which causes the useEffect
to be called again.即使数据的内容没有改变,您正在创建一个新的 object,因此它的 hash 也发生了变化,这导致再次调用
useEffect
。
If you want to initially fetch the data and set the state, then you need to pass an empty dependency array.如果你想初始获取数据并设置 state,那么你需要传递一个空的依赖数组。
useEffect(() => {
getShopifyCart()
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.