【问题标题】:Why eslint throw error when I want check array length?当我想检查数组长度时,为什么 eslint 会抛出错误?
【发布时间】:2021-10-18 13:34:50
【问题描述】:

为什么 eslint 会抛出错误( no-unused-expression )。我只是想检查数组是否为空,然后执行调度。

 useEffect(() => {
    let totalPrice = 0;
    // eslint-disable-next-line no-unused-expressions
    cart.length
      ? cart.forEach((item: AsideItemInterface) => {
        totalPrice += item.quantity * item.price;
        dispatch(setTotal(totalPrice));
      })
      : dispatch(setTotal(0));
  }, [cart]);

如果我删除 eslint-disable-next-line,则会出错。

【问题讨论】:

  • 购物车的值是异步的吗?试试cart?.length
  • 错误是什么?还有购物车在哪里定义?什么是购物车初始值?

标签: eslint


【解决方案1】:

问题是您正在编写一个具有值结果的表达式,但您没有使用该结果。更具体地说,您正在使用 ? : 运算符,例如 if 语句。解决方案是编写您实际使用的if 语句(即if (cart.length) { ... } else { ... })。

【讨论】:

    猜你喜欢
    • 2019-08-28
    • 2017-03-08
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2021-04-19
    相关资源
    最近更新 更多