2017-08-03 53 views
0

有沒有一種方法來更新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刪除的元素仍然在那裏。

任何想法?

+0

['Array.prototype.push'](https://developer.mozilla.org/ en/docs/Web/JavaScript/Reference/Global_Objects/Array/push)返回值是數組的新長度,而不是數組。 – pawel

回答

0

問題是在這一行:

const newState = oldState.push(newStateObject); 

array.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);

+0

謝謝。爲什麼'splice'不工作?它不會刪除我在Q. – Stophface

+0

中所描述的元素,做console.log(index)並檢查結果,索引應該是正確的。 –

0

Array.prototype.push不返回數組。只是push並做

this.setState({ 
    structure: oldState 
});