Reactjs React useEffect-仅在装载时运行

Reactjs React useEffect-仅在装载时运行,reactjs,eslint,create-react-app,Reactjs,Eslint,Create React App,最近,我更新了一个购物车应用程序到CRA 3,其中包括eslint插件效果。适当地,它强制依赖于useffect中的第二个参数数组 我的意图是只在mount上运行,所以我以前使用过[],它可以按预期工作,但现在它添加了这些依赖项,不在load上运行。我知道我可以全局或单独关闭此eslint规则,但我更希望知道在react中实现此功能的适当方法 const CartItem = ({ inventoryItems, dispatch, item }) => { const invItem

最近,我更新了一个购物车应用程序到CRA 3,其中包括eslint插件效果。适当地,它强制依赖于useffect中的第二个参数数组

我的意图是只在mount上运行,所以我以前使用过[],它可以按预期工作,但现在它添加了这些依赖项,不在load上运行。我知道我可以全局或单独关闭此eslint规则,但我更希望知道在react中实现此功能的适当方法

const CartItem = ({ inventoryItems, dispatch, item }) => {
  const invItem = inventoryItems.find(invItem => invItem.id === item.id);

  useEffect(() => {
  const setWarnings = (item) => {
    let warnings = [];
    if (item.quantity > invItem.quantity) {
      warnings.push(`Note quantity of requested ${
        item.name
      }s was reduced by ${item.quantity -
        invItem.quantity} due to sold inventory since it was placed in cart.`);
      item.quantity = invItem.quantity;
    }
    if (item.price !== invItem.price) {
      warnings.push(`Note price for ${
        item.name
      } has changed since it was placed in cart (${
        invItem.price > item.price ? "+ " : ""
      } ${formatPrice(invItem.price - item.price)}).`);
      item.price = invItem.price;
    }
  }
  setWarnings(item)
},[invItem.price, invItem.quantity, item])

  return (/* here I will display my item and below it map warnings array */)
}

尝试为invItem(inventoryItem)使用setState

在功能组件中设置状态。然后,您应该能够删除依赖项

const [inventoryItem, setInventoryItem] = useState(inventoryItems.find(invItem => invItem.id === item.id))

const setWarnings = (item) => { 
    // .... logic
}

useEffect(() => {
    // ...logic ( or remove it to a higher scope )
    setInventoryItem( item => {
        setWarnings(item)
        // item will = whatever the current value is and you can do your logic
   })
}, []) // I would try and override that rule regardless.
还有,你在用setWarnings做什么?它只在内部有效。删除函数声明,然后按原样调用它

这有帮助吗?我遗漏了什么吗


checkout useReducer可能很有用:

尝试使用invItem(inventoryItem)的setState

在功能组件中设置状态。然后,您应该能够删除依赖项

const [inventoryItem, setInventoryItem] = useState(inventoryItems.find(invItem => invItem.id === item.id))

const setWarnings = (item) => { 
    // .... logic
}

useEffect(() => {
    // ...logic ( or remove it to a higher scope )
    setInventoryItem( item => {
        setWarnings(item)
        // item will = whatever the current value is and you can do your logic
   })
}, []) // I would try and override that rule regardless.
还有,你在用setWarnings做什么?它只在内部有效。删除函数声明,然后按原样调用它

这有帮助吗?我遗漏了什么吗


checkout useReducer可能很有用:

仔细想想,我认为它可能会在装载时显示警告,但随后我会根据创建警告时与库存相关的更改重置项目数量和/或价格。这是合乎逻辑的(以当前的受邀价格销售,并且销售数量不超过库存),但也会在项目依赖关系发生变化时触发相应的重新招标,并快速清除提醒。我会处理好的,然后寄回来

仔细想想,我认为它可能会在装载时显示警告,但随后我会根据创建警告时与库存相关的更改重置物品数量和/或价格。这是合乎逻辑的(以当前的受邀价格销售,并且销售数量不超过库存),但也会在项目依赖关系发生变化时触发相应的重新招标,并快速清除提醒。我会处理好的,然后寄回来