警告:数组或迭代器中的每个子项都应具有唯一的"密钥"提示

Anw*_*ain -3 javascript react-native

当我使用Picker项目映射数组时,我收到以下警告:

数组中的每个子节点都应该具有唯一的"键"支柱.

这是我的代码

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>
);
Run Code Online (Sandbox Code Playgroud)

pur*_*rii 12

更好的性能

这是一个反应的建议,以提高渲染性能.通过为每个动态创建的元素提供唯一键,可以最小化可能的DOM更改.

更新您的代码

使用每个元素的id作为唯一键.或者,可以使用每个元素的索引.

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>
);
Run Code Online (Sandbox Code Playgroud)