英文:
Cleaning up state on useEffect hook
问题
有人能帮我解释一下这里可能发生了什么吗?我有一个效果,基本上,当我加载一个产品页面时,它会更新一个包含项目数组的状态,但当我更改产品(一个prop)时,它没有清除我的状态。下面是代码,有人能看出可能缺少什么吗?
const [cartItems, setCartItems] = useState<any>([]);
useEffect(() => {
if (product) {
handleCartArray(product.name, variant.sku, variant.price, product.productId);
}
return () => {
console.log('is this running?');
cleanCartItems();
};
}, [product]);
function cleanCartItems() {
console.log('I am trying to clean the cart items');
setCartItems([]);
}
这里没有太多要补充的。我正在尝试每次加载新产品时清除这个状态,但它不起作用。
英文:
Can someone give me a light on what may be happening here? I have an effect that basically, when I load a product page it updates an state with an array of items, but when I change the product (a prop) it's not cleaning up my state. The code is below, can someone see what may be missing?
const [cartItems, setCartItems] = useState<any>([]);
useEffect(() => {
if (product) {
handleCartArray(product.name, variant.sku, variant.price, product.productId);
}
return () => {
console.log('is this running?');
cleanCartItems();
};
}, [product]);
function cleanCartItems() {
console.log('I am trying to clean the cart items');
setCartItems([]);
}
Not really much to be added here. I am trying to clean up this state everytime a new product is loaded, but it isn't working.
答案1
得分: 1
确保你的 useEffect 钩子在运行(你还没有解释 product 是什么,所以我甚至不确定它是否在运行)。
另外,在 useEffect 的返回语句内调用 setCartItems([]) 怎么样?箭头语句本身就是一个函数,现在它实际上只用于回调另一个函数。
英文:
Make sure that your useEffect hook is running (you haven't explained what product is, so I'm not even sure it's running).
Also how about calling setCartItems([]) inside the the return statement in useEffect itself? The arrow statement is a function itself, right now it's literally a function only being used to callback another function.
答案2
得分: 0
useEffect
的依赖项仅在其中的代码在一个或多个依赖项的状态更改时才会触发。在你的情况下,product
似乎是一个简单的变量。使用useState
或某个集中式状态管理系统来定义product
,你的useEffect
将正常工作。祝你好运!
英文:
useEffect
dependencies only fire up the code within when the state
of one/all of the dependencies changes. In your case product
seems like a simple variable. Define product using useState
or some centralised state management system and your useEffect will work perfectly. Good luck!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论