一般是初學react的同學才會出現這樣的問題,雖然不難,卻很困擾。
這是因為數組,是引用,你雖然更新了數組,但是數組的引用地址沒有變化,react就不會認為它有變化。所以,只需要在復制的時候,對之前的數組進行深拷貝,再將新的數組set給原來的變量,就ok了。
附上之前寫的深拷貝代碼一份。
export const deepCopyObj = (obj) => { //對象及數組深拷貝
if (Object.prototype.toString.call(obj) == '[object Object]') {
var newObj = {};
for (var key in obj) {
if (Object.prototype.toString.call(obj[key]) == '[object Object]') {
var newChildObj = deepCopyObj(obj[key]);
newObj[key] = newChildObj;
} else {
newObj[key] = obj[key];
}
}
return newObj;
} else if (Object.prototype.toString.call(obj) == '[object Array]') {
let temp = []
obj.forEach((item) => {
let map;
map = deepCopyObj(item)
temp.push(map);
})
return temp
} else {
return obj
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
使用就更簡單了,
if (data) {
//設置表單的屬性
let temp = deepCopyObj(data);
setProjectList(temp)//這是函數式組件,class組件直接this.setState({list:temp})
}
- 1
- 2
- 3
- 4
- 5
- 6
ES6出來解構以后,就更更簡單了。。
state = {
list : []
}
const listTemp = [...this.state.list ] //復制數組
const index = item.index //修改位置的下標
this.setState({
UserList: UserList.map((item, idx) => idx === index ? {...item, fansId: ""} : item)
})