【问题标题】:Using Map Object to Render React Components in Order使用 Map 对象按顺序渲染 React 组件
【发布时间】:2021-12-01 15:59:13
【问题描述】:

我从我的后端收到了一个类似这样的产品对象数组。

products = [
  {id: 1, price: 10, category: "food", name: "apples"},
  {id: 2, price: 5, category: "supplies", name: "spoons"},
  {id: 3, price: 15, category: "pets", name: "cat treats"},
  {id: 4, price: 9, category: "food", name: "oranges"},
  // ...
]

我希望根据特定的优先顺序(类似于 Netflix 调整节目的方式),根据其类别将我的所有产品呈现为条带。我不希望它们以随机顺序显示,例如食物的类别条位于顶部,下一个类别条是宠物等。

我目前决定创建一个地图对象,因为它保持如下顺序:

let filteredProducts = new Map([
  ["food", []],
  ["pets", []],
  ["supplies", []],
  // ...
])  

for (let product of products) {
  let category = product["category"]
  filteredProducts.get(category).push(product)
}

目标是然后遍历map对象,从上到下返回多个类别条的React Component。

我的问题是,我不禁觉得有更有效的方法来渲染它,因为我没有看到地图对象被普遍使用。是否有更有效和常用的方法来按优先级进行过滤和渲染,或者这是否朝着正确的方向发展?

【问题讨论】:

    标签: reactjs performance rendering


    【解决方案1】:

    我相信有更简单的方法可以使用 Array sort 函数来做到这一点。 请考虑下面的 sn-p。

    
    const products = [
      {id: 1, price: 10, category: "food", name: "apples"},
      {id: 2, price: 5, category: "supplies", name: "spoons"},
      {id: 3, price: 15, category: "pets", name: "cat treats"},
      {id: 4, price: 9, category: "food", name: "oranges"},
      // ...
    ]
    
    const priority = [
      'food',
      'supplies',
      'pets'
    ]
    
    const orderedProducts = products.sort(
      (p1, p2) => priority.indexOf(p1.category) - priority.indexOf(p2.category)
    );
    
    

    让我知道这是否看起来更清洁、更简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2021-02-18
      • 2013-07-05
      • 2016-03-06
      相关资源
      最近更新 更多