[英]Replace whole object in react state
有沒有辦法用這樣的狀態結構更新state
this.state = {
structure: [
{
selected: false,
name: "a",
key: "a",
}, {
selected: false,
name: "b",
key: "b"
}, {
selected: false,
name: "c",
key: "c",
}, {
selected: false,
name: "d",
key: "d"
}
]
}
我想更新狀態。 我這樣做是這樣的:
_onPress = (obj, index) => {
const oldStateSelected = obj.selected;
const newStateObject = Object.assign({}, obj);
newStateObject.selected = !oldStateSelected;
const oldState = _.cloneDeep([...this.state.structure]);
oldState.splice(index, 1);
const newState = oldState.push(newStateObject)
this.setState({
structure: [newState]
});
}
但是,這使我回到了新的狀態
{ structure: [4] }
我認為問題在於,我是在修改現有狀態,而不是替換狀態?! 當我從array
刪除元素后console.log(oldState)
,我看到它說oldState (3) [Object, Object, Object]
。 但是當我打開它時,有4
數組元素。 我想通過splice
刪除的元素仍然在那里。
有任何想法嗎?
Array.prototype.push
不返回數組。 只是push
並做
this.setState({
structure: oldState
});
問題在這一行:
const newState = oldState.push(newStateObject);
array.push不會返回更新后的數組,當我們使用push時,它將更新原始數組,因此您需要將變量oldState值分配給狀態變量結構。
用這個:
_onPress = (obj, index) => {
const oldStateSelected = obj.selected;
const newStateObject = Object.assign({}, obj);
newStateObject.selected = !oldStateSelected;
const oldState = _.cloneDeep([...this.state.structure]);
oldState.splice(index, 1);
oldState.push(newStateObject)
this.setState({
structure: oldState //here
});
}
檢查以下代碼段:
let a = [10,15,20]; let b = a.push(20); console.log('a = ', a); console.log('b = ', b);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.