【发布时间】:2021-07-11 08:14:34
【问题描述】:
我将onClick() 事件放在元素上并尝试更改 UI 新数据,但它失败了。 podaciLjubimci 在console.log() 中根据countLike 返回我带有新数据的新状态,但UI 上什么也没有发生。
为什么数组会随着新数据发生变化并发送给我console.log() 但setState() 没有渲染组件?
代码:
const [podaciLjubimci, setState] = useState([
{ id: 1, naziv: "naziv", pol: "Muski", starost: "junuor", mesto: "Beograd", isLike: false, countLike: 1, },
{ id: 2, naziv: "naziv", pol: "Muski", starost: "junuor", mesto: "Beograd", isLike: false, countLike: 12, },
{ id: 3, naziv: "naziv", pol: "Muski", starost: "junuor", mesto: "Beograd", isLike: false, countLike: 12, },
{ id: 4, naziv: "naziv", pol: "Muski", starost: "junuor", mesto: "Beograd", isLike: false, countLike: 5, },
{ id: 5, naziv: "naziv", pol: "Muski", starost: "junuor", mesto: "Beograd", isLike: false, countLike: 2, },
{ id: 6, naziv: "naziv", pol: "Muski", starost: "junuor", mesto: "Beograd", isLike: false, countLike: 7, },
{ id: 7, naziv: "naziv", pol: "Muski", starost: "junuor", mesto: "Beograd", isLike: false, countLike: 22, },
{ id: 8, naziv: "naziv", pol: "Muski", starost: "junuor", mesto: "Beograd", isLike: false, countLike: 9, },
]);
const nepopularni = () => {
setState(podaciLjubimci.sort((a, b) => a.countLike - b.countLike));
console.log("sort", podaciLjubimci);
};
【问题讨论】:
-
所以我需要这样的数组副本: const newData = [...podaciLjubimci] 然后对该数据进行排序
标签: javascript arrays reactjs sorting use-state