React状态变量在排序时不会触发重新应答器



我想在React中实现一个可排序的表。我使用useState挂钩将表的内容作为数组存储在状态变量中。现在,当我对数组进行排序并更新内容状态变量时,我希望表在更新状态后重新呈现。不幸的是,事实并非如此,并且该表不显示排序。这是我的问题的简化版本。当我点击表的标题字段"时;名称";我触发了状态的排序和更新,但它不会重新发送。知道我缺了什么吗?

import { useState, useEffect } from 'react';
function App() {
type Entry = {
id: number;
name: string;
};
const [collection, setCollection] = useState<Entry[]>([]);
useEffect(()=> {
// just initially populating collection with data for testing purposes
setCollection([{id:1, name:"Ben"}, {id:2, name:"John"}, {id:3, name:"Anna"}])
}, [])
const byName = (a: Entry, b: Entry) => {
let x = a.name.toLowerCase();
let y = b.name.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
}
return (
<div>
<table>
<tr id="head">
<th>Id</th>
<th onClick={() => setCollection(collection.sort(byName))}>Name</th>
</tr>
{collection.map((val, index) => 
<tr id={index.toString()}>
<td>{val.id}</td>
<td>{val.name}</td>
</tr>
)}
</table>
</div>
);
}

sort函数将排序在适当的位置并返回相同的引用,因此您正在改变状态,而不是更新它。

进行

<th onClick={() => setCollection([...collection].sort(byName))}>Name</th>

最新更新