2017-08-29 36 views
2

我試圖呈現從JSON獲取從API一個FlatList,但我不斷收到此錯誤:陣營母語:無法修復FlatList鍵警告

Warning: Each child in an array or iterator should have a unique "key" prop. 
Check the render method of `VirtualizedList`. 

相關代碼:

<FlatList 
    data={this.props.tunes} 
    keyExtractor={(item, index) => item.id} 
    renderItem={({item}) => { 
    <Item 
     key={item.id} 
     title={item.title} 
     composer={item.composer} 
     year={item.year} 
    /> 
    }} 
/> 

我相信這有一個簡單的解決方法,但在嘗試不同的事情幾天後,我還沒有找到它。謝謝你的幫助!

+0

你確定item.id是不同的每個項目?並確保數據中沒有重複的項目。 – bennygenel

+0

也許這是我困惑的地方。 json中沒有item.id,但我想可能React會在這種情況下提供它。在將數據提供給FlatList之前,我是否必須將json映射到每個項目上並添加一個id? – Thomas

+0

你需要自己創建密鑰。你可以像'item.name + index'那樣做一些事情,或者對每個項目可以是獨一無二的,並且不會改變 – bennygenel

回答

3

看起來你需要改變keyid您在keyExtractoritem.id,並確保你有ID,它是爲每個組件不同:

<FlatList 
    data={this.props.tunes} 
    keyExtractor={(item, index) => item.id} 
    renderItem={({item}) => { 
    <Item 
     id={item.id} //instead of key 
     title={item.title} 
     composer={item.composer} 
     year={item.year} 
    /> 
    }} 
/> 

或者,如果你不具備的獨特鍵使用keyExtractor={(item, index) => index}

+0

感謝您在keyExtractor中的item.id –