【发布时间】:2021-12-31 04:50:01
【问题描述】:
所以我试图通过使用状态对对象数组进行非破坏性的字母顺序排序,因此我也可以将数组返回到其原始排列。我已经尝试了很多将原始数组复制到新数组中进行排序的方法:JSON methods to carry a deep copy of this.props.getDaycare.toddlers:
constructor(){
super()
this.state = {
newArray: []
}
}
sort = () => {
let initialArray = this.props.getDaycare.toddlers
let copiedInitialArray = JSON.parse(JSON.stringify(initialArray));
console.log(copiedInitialArray)
this.setState({
newArray: copiedInitialArray.sort((t,u) =>{
if (t.name < u.name) {return -1;}
if (t.name > u.name) {return 1;}
return 0;
})
})
}
这似乎不起作用。它根本没有更新 DOM,但是当我单击排序按钮时,它在控制台中(按字母顺序)更新了
0: {id: 84, name: 'Jared Leno', birthday: '2019-09-02', contact: 'Poppy Roberts', phone: 7605551919, …}
1: {id: 88, name: 'Massimo Gandolfini', birthday: '2019-01-06', contact: 'Poppy Roberts', phone: 7605551919, …}
2: {id: 87, name: 'Rosie Perez', birthday: '2018-12-22', contact: 'Poppy Roberts', phone: 7605559091, …}
3: {id: 80, name: 'Samantha Madison', birthday: '2019-01-06', contact: 'Olusoji Akinremi', phone: 7605551919, …}
4: {id: 90, name: 'Sara Waters', birthday: '2018-12-22', contact: 'Jessica Smith', phone: 7605559091, …}
5: {id: 83, name: 'Serena Williams', birthday: '2019-01-06', contact: 'Sara Reynolds', phone: 7605551919, …}
length: 6
[[Prototype]]: Array(0)
我也尝试过浅拷贝方法,例如spread、slice、from。请注意,不更新 DOM 而是在控制台中输出的结果相同。我已经在网上到处寻找这个特定问题,但我还没有看到任何示例显示如何有效地深度复制对象数组以进行排序。所有示例都对原始数组具有破坏性。
我想知道有什么办法吗?请帮忙。
【问题讨论】:
标签: javascript arrays reactjs sorting javascript-objects