在 useEffect 钩子上清理状态

huangapple go评论56阅读模式
英文:

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!

huangapple
  • 本文由 发表于 2023年7月12日 22:04:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定