如何在深度嵌套对象发生变化时触发useEffect?

问题描述 投票:0回答:1

我有一个如下所示的对象:

{
  "selectedProducts": [
    {
      "selectionId": 1722249608951,
      "productId": "8174367932666",
      "variants": [
        {
          "variantId": "45186237989114",
          "price": "17.99",
          "title": "Chicken",
          "quantity": 1
        },
        {
          "variantId": "45186238021882",
          "price": "18.99",
          "title": "Beef",
          "quantity": 1
        },
        {
          "variantId": "45186238054650",
          "price": "16.99",
          "title": "Mushroom",
          "quantity": 1
        }
      ],
      "productTitle": "Burger"
    },
    {
      "selectionId": 1722249804165,
      "productId": "8174367932666",
      "variants": [
        {
          "variantId": "45186237989114",
          "price": "17.99",
          "title": "Chicken",
          "quantity": 1
        },
        {
          "variantId": "45186238021882",
          "price": "18.99",
          "title": "Beef",
          "quantity": 1
        }
      ],
      "productTitle": "Burger (2)"
    }
  ]
}

现在我想在

useEffect
内的变体计数发生更改时触发
selectedProducts
。所以我最初尝试执行以下操作:

useEffect(() => {
  // Some Operations

  setFormState((prevState) => ({
    ...prevState,
    ...productOptions,
  }));

}, [
  ...formState.selectedProducts.map((product) => product.variants.length)
]);

但这会产生如下错误:

Warning: The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant.


因此,我实现的方法是采用另一个

state
来存储 变体总数,然后将
selectedProducts
作为另一个
useEffect
的依赖项传递,然后将更改
totalVariantsCount
。然后将
totalVariantsCount
作为主
useEffect
的依赖项传递,我想在变体计数发生变化时在该位置触发。

const [totalVariantsCount, setTotalVariantsCount] = useState(0);

useEffect(() => {
    const variantsCount = formState.selectedProducts.reduce(( acc, product ) => acc + product.variants.length, 0);
    setTotalVariantsCount(variantsCount);

}, [formState.selectedProducts]);

为了检查它,我实施了以下操作:

useEffect(() => {
  console.log(`totalVariantsCount changed: ${totalVariantsCount}`);

  // REMOVE: Putting the value in the formState just for test, remove it when releasing.  
  setFormState((prevState) => ({ ...prevState, totalVariantsCount }));

}, [totalVariantsCount]);

这目前有效,但有时表现得很奇怪 - 当在

useEffect
更改后触发此
totalVariantsCount
时,它
consoleLogs
每次都是正确的值,但仅在以下情况下才更改主
totalVariantsCount
中的
formState
selectedProducts
计数不会在变体计数更改时更改。


所以我想知道在更改深层嵌套对象时触发

useEffect
的正确方法是什么。

谢谢!

reactjs react-hooks
1个回答
0
投票

我认为你需要使用整个数组并进一步检查使用效果,这answer可以帮助:

© www.soinside.com 2019 - 2024. All rights reserved.