sku*_*ler -1 reactjs react-router
我正在尝试按日期和数字对 JSON 对象进行排序。当我控制台日志时一切正常,但状态没有在 GUI 端更新。我错过了什么?我正在使用功能组件。这是代码...
const Posts = () => {
const [dummyData, setDummyData] = useState(Data);
const sortList = (e) => {
if (e.target.value === "date") {
handleSort();
} else if (e.target.value === "upvotes") {
byUpvotes();
}
};
const handleSort = () => {
const sortedData = dummyData.sort((a, b) => {
const c = new Date(a.published);
const d = new Date(b.published);
if (c.getDate() > d.getDate()) {
return c;
} else {
return d;
}
});
setDummyData(sortedData);
console.log(sortedData);
};
const byUpvotes = () => {
const sortByName = dummyData.sort((a, b) => {
return b.upvotes - a.upvotes;
});
setDummyData(sortByName);
console.log(sortByName);
};
return (
<div>
{dummyData.map((post) => (
<PostsItem key={post.id} post={post} />
))}
<div className="row">
<div className="col-s6">
<label>Browser Select</label>
<select className="browser-default" onChange={sortList}>
<option disabled selected>
Choose your option
</option>
<option value="date">Date</option>
<option value="upvotes">Upvotes</option>
</select>
</div>
</div>
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
sort 函数不会创建新数组,它会改变旧数组。因此,您正在重新排列现有状态,然后使用相同的数组设置状态。由于它是同一个数组,react 认为状态没有改变并跳过渲染。
相反,您需要制作数组的副本,然后对其进行排序。例如:
const byUpvotes = () => {
const sortByName = [...dummyData];
sortByName.sort((a, b) => {
return b.upvotes - a.upvotes
})
setDummyData(sortByName)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |