【问题标题】:Why this sort function is not returning to the original order?为什么这个排序函数没有返回到原来的顺序?
【发布时间】:2021-05-26 14:16:09
【问题描述】:

我有一个排序功能。 productList || filteredInfos 是从父组件传下来的数据数组

const sortItems = (data) => {
    let priceArray = [];
    if (filteredState === true) {
      priceArray = filteredInfos;
    } else {
      priceArray = productList;
    }

    if (data === 'Price low - high') {
      priceArray.sort(
        (a, b) => a.discountedPriceWithDouble - b.discountedPriceWithDouble,
      );
    } else if (data === 'Price high - low') {
      priceArray.sort(
        (a, b) => b.discountedPriceWithDouble - a.discountedPriceWithDouble,
      );
    } else {
      priceArray = productList;
    }
    setFilteredInfos(priceArray);
  };

我不明白的是if 条件。排序价格 low-highhigh-low 正在工作,但在 else 声明中,我相信我将此数据更改回原始顺序。 但是 else 语句不起作用。数据始终按价格high-lowlow-high 排序

我如何呈现数据

<FlatList
    //bikelist is the data from productList || filteredInfos
    data={bikeList}
    renderItem={renderItem}
    keyExtractor={(item, index) => String(index)}
    style={styles.arrayListMargin}
/>

【问题讨论】:

  • 无法检查几分钟前非常相似的已关闭问题(现在已删除)是否存在差异,这里有区别吗?
  • 有人可以解释为什么这个问题会得到 - 。旧问题已被删除,因为有人提出了一个不能解决问题本身的答案
  • priceArray = productList 不会复制productList
  • @ASDFGerte 您能否在结束问题之前至少发表评论。您建议的旧问题根本无法解决我的问题。在旧情况下
  • 我没有关闭你的旧问题,我也没有完全阅读它,因为它已经关闭了。但是,如果我意识到,我在五分钟内看到了已关闭问题的转发,并且旧问题已被删除,所以我无法检查我是否只是收到垃圾邮件,我认为我是。

标签: javascript reactjs


【解决方案1】:

您可以通过分散项目来获取数组的副本。

const sortItems = (data) => {
    const
        directions = {
            'Price low - high': 1,
            'Price high - low': -1
        },
        order = directions[data];
        priceArray = filteredState && order
            ? [...filteredInfos]
            : [...productList],

    if (order) {
        priceArray.sort((a, b) => order * (a.discountedPriceWithDouble - b.discountedPriceWithDouble));
    }

    setFilteredInfos(priceArray);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    相关资源
    最近更新 更多