将 json 响应中的 id 映射到键并将其用于 FlatList react-native
mapping id from json response to key and use it for 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" 属性。
现在我可以遍历数组中的每个项目并添加一个 属性 "key" ,它与 ID 具有相同的值。但我觉得这很有效。
是否有更好的方法将 "id" 列映射到 "key" 以呈现 FlatList
我能看到这种情况发生的最快方法是遍历数组。
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":""}]
尝试使用 keyExtractor 。请将您的代码更新为:
return(
<View>
<FlatList
data={this.state.centres}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => <CentreComponent centre={item}/>}
/>
</View>
);
我从 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" 属性。
现在我可以遍历数组中的每个项目并添加一个 属性 "key" ,它与 ID 具有相同的值。但我觉得这很有效。
是否有更好的方法将 "id" 列映射到 "key" 以呈现 FlatList
我能看到这种情况发生的最快方法是遍历数组。
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":""}]
尝试使用 keyExtractor 。请将您的代码更新为:
return(
<View>
<FlatList
data={this.state.centres}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => <CentreComponent centre={item}/>}
/>
</View>
);