React useEffect-仅在安装上运行

时间:2019-04-24 20:42:02

标签: reactjs eslint create-react-app

最近,我将购物车Appt更新为CRA 3,其中包括eslint-plugin-react-hooks useEffect。适当地,它会强制依赖useEffect中的第二个参数数组。

我的意图是仅在mount上运行,因此我以前使用过[]并且可以按预期工作,但是现在它添加添加了这些依赖项,并且不在负载下运行。我知道我可以全局或单独关闭此eslint规则,但我更想知道适当的方法来完成此操作。

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 */)
}

2 个答案:

答案 0 :(得分:0)

尝试将setState用于invItem(inventoryItem)。

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

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做什么?它仅在useEffect内部可用。删除函数声明,然后像您一样调用它。

此帮助有用吗,我是否有任何遗漏?

结帐useReducer可能有用:https://testdriven.io/blog/react-hooks-advanced/

答案 1 :(得分:0)

考虑得更多,我认为它可能会在安装时带有警告,但是我会根据警告创建过程中与库存相关的更改来重置商品数量和/或价格。这是合乎逻辑的(以当前invItem的价格出售,并且不会卖出超过库存的价格),而且还可以触发随项目依赖关系变化而进行的适当重新渲染,并迅速清除提醒。我将进行处理并发回。