2017-07-11 25 views
1

我有如下的API響應一個JSON:映射ID並將其用於FlatList反應天然

centres = [{ 
    id: 1, 
    name: "DEF", 
    },{ 
    id: 2, 
    name: "ABC", 
    }] 

現在我要填充在FlatList

上述數據
return(
    <View> 
    <FlatList 
     data={this.state.centres} 
     renderItem={({item}) => <CentreComponent centre={item}/>} 
    /> 
    </View> 
); 

但我不能做以上的數據(中心)沒有「關鍵」財產。

現在我可以遍歷數組中的每個項目並添加一個屬性「key」,它具有與ID相同的值。但我認爲這是有效的。

是否有更好的方法來映射「ID」欄爲「關鍵」,以使FlatList

+0

https://stackoverflow.com/questions/21148419/efficiently-rename-re-map-javascript-json-object-keys-within-array-of-objects的可能的複製 – Dominik

+0

嗯不完全。這篇文章提到通過解析一個字符串來取代,而這是一個JSON對象。 –

+0

沒錯。儘管關閉。 ;) – Dominik

回答

1

嘗試使用keyExtractor。請更新您的代碼:

return(
<View> 
    <FlatList 
    data={this.state.centres} 
    keyExtractor={(item, index) => item.id} 
    renderItem={({item}) => <CentreComponent centre={item}/>} 
    /> 
    </View> 
); 
1

的fastes方法可以讓我看到這樣的情況是通過遍歷數組了。

const centres = [{ 
    id: 1, 
    name: "DEF", 
    },{ 
    id: 2, 
    name: "ABC", 
}]; 

const newCentres = centres.map((item) => ({ key: item.id, name: item.name })); 

console.log(JSON.stringify(newCentres)) 
// [{"key":1,"name":""},{"key":2,"name":""}]