【问题标题】:Sort method is not working with useState() in React排序方法不适用于 React 中的 useState()
【发布时间】: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


【解决方案1】:

使用以下代码:

setState(podaciLjubimci.sort((a, b) => a.countLike - b.countLike))

您正在改变状态数据,因为sort() 方法就地对数组的元素进行排序并返回排序后的(相同的引用,而不是新的) 数组。这就是您的控制台日志显示已排序数据但 it does not re-render the component 的原因。

要在不改变原始数据的情况下对状态数据进行排序,您需要在排序前浅拷贝数组。

一个例子:

setState([].concat(podaciLjubimci).sort((a, b) => a.countLike - b.countLike))

PS:有很多方法可以浅拷贝数组。例如,您可以使用.slice()、展开语法、concat() 或.map()。

【讨论】:

  • @max 我已经看到你的问题了。您需要在排序之前对数组进行浅拷贝(如本文所示)。
  • 哦,我想我理解 customerList.map(val,key) .sort() 对吧?
猜你喜欢
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2022-07-19
  • 2021-09-28
  • 1970-01-01
  • 2019-07-07
相关资源
最近更新 更多