【问题标题】:How to refresh cart if there is no product left?如果没有产品,如何刷新购物车?
【发布时间】:2022-01-18 00:49:14
【问题描述】:

我每次都需要刷新我的购物车页面,当 products.length 为 0 但我不知道如何编写 if 条件时,现在它编写了无法访问的代码。 我觉得这很简单,所以我在这里问。

 switch (action.type){ 
     case "REMOVE_PRODUCT":
      return products.filter((p) => p.id !== action.productId);
      if (products.length === 0) {
        window.location.reload();
      }
}

【问题讨论】:

    标签: javascript html reactjs react-native


    【解决方案1】:

    好吧,您的代码无法访问,因为它位于 return 语句之后,因此请将其更改为以下内容:

    switch (action.type) { 
      case "REMOVE_PRODUCT":
        const data = products.filter((p) => p.id !== action.productId);
        if (data.length === 0) {
          window.location.reload();
        }
        return data;
    }
    

    注意:如果您使用redux,看起来,最好在使用数据的组件中处理此逻辑,而不是在这里。

    【讨论】:

    • 这个case 可能会工作,但case 块内有一个返回,并且 linter 会抱怨。
    • 检查编辑,结果基本相同,但没有 linter 问题,或者至少不应该。
    • 我会从效果或类似的东西“调用”这个caseuseEffect(() => { if (!products.length) dispatch({type: 'REMOVE_PRODUCT'}); }, [products.length]);
    • 做得很好,这看起来很完美
    【解决方案2】:

    在签入 IF 块之前返回时,您会收到code unreachable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 2013-05-02
      • 2012-06-29
      • 1970-01-01
      • 2018-03-04
      相关资源
      最近更新 更多