我會盡力描述你的情況。我有一個組件狀態是對象數組和組件將根據這些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組件。它的item1用item2重置道具。這種行爲混淆了我的應用程序的邏輯。有什麼辦法可以避免這種行爲? 因爲另一個組件的主邏輯是在componentDidMount方法組件並不真正更新我需要的方式。 您可以想像某種聊天應用程序,其中AnotherComponent組件是聊天室。當componentDidMount方法執行時,它連接到遠程服務器以獲取新消息。因爲這個邏輯只執行一次,所以當應用程序狀態如我在狀態操作的最後一個例子中所描述的那樣發生變化時(當您從狀態中刪除item1聊天室並在應用程序中打開item2時),實際上您會看到item1聊天室剛剛關閉。 (這與我現在面臨的問題非常相似)
希望你能理解我寫的內容。謝謝。
哦..現在我明白你爲什麼需要這個關鍵屬性。 React給了我一個警告,我應該傳遞一些值給這個關鍵屬性,所以我只是通過了狀態中項目的索引。謝謝 – harumando