有沒有一種方法來更新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] }
一個新的狀態,我認爲這個問題是,我modifiing到位的狀態,而不是取代它的? 當我從array
中刪除元素後,我看到它說oldState (3) [Object, Object, Object]
。 但是當我打開它時,有4
數組元素。我想用splice
刪除的元素仍然在那裏。
任何想法?
['Array.prototype.push'](https://developer.mozilla.org/ en/docs/Web/JavaScript/Reference/Global_Objects/Array/push)返回值是數組的新長度,而不是數組。 – pawel