【问题标题】:React useEffect - Run on Mount OnlyReact useEffect - 仅在挂载上运行
【发布时间】:2019-04-24 20:42:01
【问题描述】:

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

我的意图是只在挂载时运行,所以我之前使用过 [] 并且它按预期工作,但现在它添加了这些依赖项并且不会在加载时运行。我知道我可以全局或单独关闭此 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 */)
}

【问题讨论】:

    标签: reactjs eslint create-react-app


    【解决方案1】:

    尝试对 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 做什么?它仅在 useEffect 中可用。删除函数声明并像你一样调用它。

    这有帮助吗?我错过了什么吗?

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

    【讨论】:

      【解决方案2】:

      再想一想,我认为它可能会在安装时呈现警告,但随后我会根据创建警告时与库存相关的变化来重置项目数量和/或价格。这是合乎逻辑的(以当前的 invItem 价格出售,并且不超过库存),但也会触发适当的重新渲染,因为项目依赖性正在发生变化并快速清除提醒。我会处理它并回帖。

      【讨论】:

        猜你喜欢
        • 2020-04-16
        • 2022-09-27
        • 2020-09-07
        • 1970-01-01
        • 2020-10-22
        • 2020-10-17
        • 1970-01-01
        • 2021-08-09
        相关资源
        最近更新 更多