所以我試圖通過使用 state 以非破壞性的方式按字母順序對物件陣列進行排序,因此我也可以將陣列回傳到其原始排列。我已經嘗試了很多將原始陣列復制到新陣列中進行排序的方法: JSON 方法來攜帶以下內容的深層副本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 但在控制臺中輸出的結果相同。我已經在網上到處尋找這個特定問題,但沒有看到任何示例顯示如何有效地深度復制物件陣列以進行排序。所有的例子都破壞了原始陣列。
我想知道有什么辦法嗎?請幫忙。
uj5u.com熱心網友回復:
- 要復制 JS 陣列,您可以使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361718.html標籤:javascript 数组 反应 排序 javascript对象
