2016-08-24 95 views
1

我在使用我的React應用程序中的react-addons-update npm軟件包,並且特別想使用update()方法在對象數組內插入新對象。 我有這樣的結構作爲我的組件的狀態的一部分:react-addons-update - 如何在對象數組中深入插入對象?

... 
constructor(props) { 
    super(props); 
    this.state = { 
     blocks: [ 
      { 
       block_title: "some title", 
       items: [ 
        { 
         item_title: "foo" 
        }, 
        { 
         item_title: "bar" 
        } 
       ] 
      }, 
      { 
       ... 
      } 
     ] 
    }; 
} 
... 

,我想插入一個新項目插入到items陣列,所述第一和第二項之間。

我已經試過這樣:

... 
insertItem(){ 
    let obj = { 
     item_title: "in between foo and bar" 
    }; 
    this.setState({ 
     blocks: update(this.state.blocks, { 
      [0]: { 
       items: {$splice: [[1, 0, obj]]} 
      } 
     }) 
    }); 
} 
... 

但這似乎並沒有工作(沒有錯誤被拋出其一)。有任何想法嗎?

p.s.我在Meteor應用程序中使用React - 以防萬一有一些怪癖阻止這個幫助函數的工作。

+0

什麼是更新方法也被提到?塊是不可變的列表嗎?如果是這樣,我認爲你需要使用'updateIn',你需要在將數組傳遞給'updateIn'方法之前分別重建數組。 – RocketGuy3

+0

update()方法是react-addons-update npm包中的一個輔助函數。 – JoeTidee

+1

看起來像你的代碼應該工作。它可能與更新不同有關嗎?如果你要記錄你的更新函數,結果如何? –

回答

0

無法在組件中看到您的其他方法,但請嘗試確保您爲呈現的添加項呈現的元素上的按鍵道具是唯一的。

+0

我使用console.log打印出更新後的'塊'的狀態,所以有一個關鍵在這種情況下不相關.. – JoeTidee

+1

您的console.log在componentDidUpdate或渲染? setState異步更新狀態,所以狀態可能不會立即在setState之後更新。 – goldbullet

0

根據goldbullet的評論,setState異步更新組件狀態。我發現代碼塊中setState後面的進程實際上是在組件狀態更新之前得到的。因此,原始問題中的上述語法對於在對象數組內插入對象是正確的。

作爲一個解決方案,我用的setState回調選項如下:

... 
insertItem(){ 
    let obj = { 
     item_title: "in between foo and bar" 
    }; 
    this.setState({ 
     blocks: update(this.state.blocks, { 
      [0]: { 
       items: {$splice: [[1, 0, obj]]} 
      } 
     }) 
    },function(){ 
     // DO SOMETHING HERE!! 
    }); 
} 
... 

這在這個崗位Why calling react setState method doesn't mutate the state immediately?