2016-09-03 91 views
1

我會盡力描述你的情況。我有一個組件狀態是對象數組和組件將根據這些objects.So我們有這樣的事情使另一個組件:刪除組件而不是更新

class MainComponent extends React.Component { 
    render(){ 
    return this.state.items.map((item) => { 
     return <AnotherComponent {...item} />) 
    } 
    } 
} 

所以,如果我們在狀態,結果就會像3項這個:

<MainComponent> 
    <AnotherComponent item1 /> 
    <AnotherComponent item2 /> 
    <AnotherComponent item3 /> 
</MainComponent> 

現在讓我們對狀態進行一些操作。如果我們從狀態刪除最後一個元素,組件將被重新描繪爲這樣:

<MainComponent> 
    <AnotherComponent item1 /> // nothing happens to this one 
    <AnotherComponent item2 /> // and to this one 
         // this element is deleted 
</MainComponent> 

但是,如果我們從狀態刪除第一個元素,組件將被重新描繪爲這樣:

<MainComponent> 
    <AnotherComponent item2 /> 
    <AnotherComponent item3 /> 
</MainComponent> 

item2在這種情況下實際上並不是item2組件。它的item1item2重置道具。這種行爲混淆了我的應用程序的邏輯。有什麼辦法可以避免這種行爲? 因爲另一個組件的主邏輯是在componentDidMount方法組件並不真正更新我需要的方式。 您可以想像某種聊天應用程序,其中AnotherComponent組件是聊天室。當componentDidMount方法執行時,它連接到遠程服務器以獲取新消息。因爲這個邏輯只執行一次,所以當應用程序狀態如我在狀態操作的最後一個例子中所描述的那樣發生變化時(當您從狀態中刪除item1聊天室並在應用程序中打開item2時),實際上您會看到item1聊天室剛剛關閉。 (這與我現在面臨的問題非常相似)

希望你能理解我寫的內容。謝謝。

回答

1

您可以使用關鍵的動態項目。

class MainComponent extends React.Component { 
    render(){ 
    return this.state.items.map((item) => { 
     return <AnotherComponent key={item.id} {...item} />) 
    } 
    } 
} 

在這種情況下,我認爲該項目有一個ID來區分每個對象

如果REACT調和鍵控孩子,這將確保與關鍵任何的孩子將被重新排序(而不是破壞)或摧毀(而不是重用)。

該鍵應始終直接提供給數組中的組件,而不是數組中每個組件的容器HTML子代。

參考:Dynamic Children

+0

哦..現在我明白你爲什麼需要這個關鍵屬性。 React給了我一個警告,我應該傳遞一些值給這個關鍵屬性,所以我只是通過了狀態中項目的索引。謝謝 – harumando

相關問題