如何使用react在javascript中对从端点获取的数据进行排序



我想根据物品的Id升序对其进行排序,那么如何做到呢?

这是我使用的react组件的代码。。。

import { useState, useEffect} from "react"
//styles
import './ItemList.css'
export default function ItemList() {
const[Items,setItems]=useState([])

useEffect(() => {
fetch('http://localhost:3000/data')
.then(response=>response.json())
.then(json=>setItems(json))

}, [])

console.log(Items)
return (
<div className="item-list">
<h1>Item List</h1>
<ul>
{Items.map(data=>(
<li key={data.id}>
<h2>{data.id}</h2>
<h3>{data.name}</h3>
</li>
))}
</ul>

</div>
)
}

如果在前端进行排序,分页可能会产生问题。

前端使用数组排序,我假设id是数字

fetch("http://localhost:3000/data")
.then((response) => response.json())
.then((json) => setItems(json.sort((a, b) => a.id - b.id)));

如果是字符串

fetch("http://localhost:3000/data")
.then((response) => response.json())
.then((json) => setItems(json.sort()));

最新更新