[英]Warning: Each Child in an Array or Iterator Should Have a Unique “Key” Prop
When i map an array with Picker item i got the following warning:当我使用 Picker 项目映射数组时,我收到以下警告:
Each child in an array should have a unique "key" prop.
数组中的每个孩子都应该有一个唯一的“键”道具。
Here is my code这是我的代码
var locationArray = [{"name":"canada","id":"2"},{"name":"sweden","id":"3"}];
var Locations = locationArray.map(function(result) {
return <Picker.Item label={result.name} value={result.id} /> ;
});
return (
<ScrollView contentContainerStyle={styles.contentContainer}>
<View style={styles.container}>
<Picker selectedValue={this.state.location} onValueChange={(location) => this.setState({location:location})} style={[styles.picker, {color: '#2E3740'}]}>
{Locations}
</Picker>
</View>
</ScrollView>
);
This is a suggestions of reactjs to improve the rendering performance.这是 reactjs 提升渲染性能的建议。 By providing a unique key for each dynamically created element, it is possibile to minimize possible DOM changes.
通过为每个动态创建的元素提供唯一的键,可以最大限度地减少可能的 DOM 更改。
Use the id of each element as a unique key.使用每个元素的 id 作为唯一键。 Alternatively would it be possible to use the index of each element.
或者,是否可以使用每个元素的索引。
var locationArray = [{"name":"canada","id":"2"},{"name":"sweden","id":"3"}];
var Locations = locationArray.map(function(result) {
return <Picker.Item key={result.id} label={result.name} value={result.id} /> ;
});
return (
<ScrollView contentContainerStyle={styles.contentContainer}>
<View style={styles.container}>
<Picker selectedValue={this.state.location} onValueChange={(location) => this.setState({location:location})} style={[styles.picker, {color: '#2E3740'}]}>
{Locations}
</Picker>
</View>
</ScrollView>
);
Even I faced the same warning message and was able to overcome it by adding a unique key to the return object like in the below code.甚至我也遇到了同样的警告消息,并且能够通过向返回对象添加一个唯一键来克服它,如下面的代码所示。
Code with warning message带有警告信息的代码
getBatchList() {
return this.state.availableBatch.map((data) => {
return (
<RadioButton value={data.label}>
<Text style={styles.batchText}>{data.label}</Text>
</RadioButton>
)
})
}
Code without warning message没有警告信息的代码
getBatchList() {
//LIKE THIS
var keyId=1;
return this.state.availableBatch.map((data) => {
return (
<RadioButton value={data.label} key={keyId}>
<Text style={styles.batchText}>{data.label}</Text>
</RadioButton>
)
keyId = keyId+1;
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.