reactjs - 如何在 React 中按升序对过滤器下拉列表中的 UniqueValues 进行排序
问题描述
我是 React 新手,一直无法找到在过滤器中对唯一值进行排序的解决方案。我有一个过滤器下拉列表,其中列出了 UniqueValues(年)以及来自 Airtable 无服务器函数的数据。我想按升序对年份进行排序。目前,这是过滤器以随机顺序显示年份的方式:
这是我来自 Filter.js 页面的代码。要清楚我要排序的过滤器是 year :
import React from "react";
import styled from "styled-components";
import { useFilterContext } from "../context/filter_context";
import { getUniqueValues, formatPrice } from "../utils/helpers";
import { FaCheck } from "react-icons/fa";
const Filters = () => {
const {
filters: { text, year, shape, themecamp, official },
updateFilters,
all_products,
clearFilters,
} = useFilterContext();
const years = getUniqueValues(all_products, "year");
const shapes = getUniqueValues(all_products, "shape");
return (
<Wrapper>
<div className="content">
<form onSubmit={(e) => e.preventDefault()}>
{/* start search input */}
<div className="form-control">
<input
type="text"
name="text"
placeholder="search"
className="search-input"
value={text}
onChange={updateFilters}
/>
</div>
{/* end of search input */}
{/* start clear filters */}
<button type="button" className="clear-btn" onClick={clearFilters}>
clear filters
</button>
{/* end clear filters */}
{/* start year */}
<div className="form-control">
<h5>year</h5>
<select
name="year"
value={year}
onChange={updateFilters}
className="year"
>
{years.map((stickeryear, index) => {
return (
<option key={index} value={stickeryear}>
{stickeryear}
</option>
);
})}
</select>
</div>
{/* end of year */}
{/* sticker shape */}
<div className="form-control">
<h5>sticker shape</h5>
<select
name="shape"
value={shape}
onChange={updateFilters}
className="shape"
>
{shapes.map((c, index) => {
return (
<option key={index} value={c}>
{c}
</option>
);
})}
</select>
</div>
{/* end sticker shape */}
{/* start themecamp */}
<div className="form-control themecamp">
<label htmlFor="themecamp">Theme Camps</label>
<input
type="checkbox"
name="themecamp"
id="themecamp"
checked={themecamp}
onChange={updateFilters}
/>
</div>
{/* end of themecamp */}
{/* start official sticker */}
<div className="form-control themecamp">
<label htmlFor="official">"Official sticker"</label>
<input
type="checkbox"
name="official"
id="official"
checked={official}
onChange={updateFilters}
/>
</div>
{/* end of official sticker */}
</form>
</div>
</Wrapper>
);
};
export default Filters;
解决方案
通过添加解决:
years.sort(compareYears);
function compareYears(a, b) {
return b - a;
}