如何根据不同的属性对 React 组件列表进行排序?

Ali*_*rra 11 reactjs redux

所以,这是我前端的代码片段。

{store.results.data.map( result =>
  <ResultItem 
    key={result.id}
    title={result.title}
    description={result.description}
    start_date={result.start_date}
    end_date={result.end_date}
    vendor_name={result.vendor.name}
    buyer_name={result.buyer.name}
    preview_file={result.preview_file}
    status={result.status}
  />
)}
Run Code Online (Sandbox Code Playgroud)

基本上,我将 Redux 存储中的所有数据映射到 ResultItems。我希望能够ResultItems按不同的属性对我的所有内容进行排序,例如title, description, start_date, end_date, vendor_name, 和buyer_name

关于如何做到这一点的任何想法?

use*_*105 7

我会创建一个 Sort 组件并用它包装结果项,如下所示:

<Sort by='title'>
{store.results.data.map( result =>
  <ResultItem 
    key={result.id}
    title={result.title}
    description={result.description}
    start_date={result.start_date}
    end_date={result.end_date}
    vendor_name={result.vendor.name}
    buyer_name={result.buyer.name}
    preview_file={result.preview_file}
    status={result.status}
  />
)}
</Sort>

// Note: The 'by' prop passed into <Sort> in my example is hardcoded by you can grab it from redux or set it when user selects something from a list. Also you can pass another prop to indicate whether to sort by ascending or descending order etc

Run Code Online (Sandbox Code Playgroud)

然后在 Sort 组件中,您可以像这样访问结果项的数组,并对数组React.Children.toArray使用 sort 方法并将 sort 方法传递给“比较”函数。

// Sort.js

import React from 'react';

// Compare function needed by the Sort component
const compare =(a, b) => {
    // you can access the relevant property like this a.props[by]
// depending whether you are sorting by tilte or year, you can write a compare function here, 

  }

const Sort= ({children, by})=> {
If (!by) {
// If no 'sort by property' provided, return original list
return children
}
return React.Children.toArray(children).sort(compare)

}
Run Code Online (Sandbox Code Playgroud)

上面的主要优点是您可以在其他任何地方使用 Sort 组件,并且您可以将排序逻辑与初始结果的映射巧妙地分开。


Rod*_*ius 2

在进行地图部分之前,您必须对数据进行排序。例如,假设您想按 id 排序:

    {store.results.data.sort((a, b) => a.id - b.id).map( result =>
            <ResultItem key={result.id}
            title={result.title}
            description={result.description}
            start_date={result.start_date}
            end_date={result.end_date}
            vendor_name={result.vendor.name}
            buyer_name={result.buyer.name}
            preview_file={result.preview_file}
            status={result.status}
   />)}
Run Code Online (Sandbox Code Playgroud)