将json响应中的id映射到key,并将其用于FlatList react-native
我有一个API的JSON响应如下:
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
尝试使用keyExtractor 。 请更新您的代码:
return( <View> <FlatList data={this.state.centres} keyExtractor={(item, index) => item.id} renderItem={({item}) => <CentreComponent centre={item}/>} /> </View> );
我可以看到这种情况的方式是迭代数组。
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":""}]