警告:数组或迭代器中的每个子代均应具有唯一的“键”道具检查`ListView`的渲染方法

【字号: 日期:2024-04-17浏览:37作者:雯心
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解决警告:数组或迭代器中的每个子代均应具有唯一的“键”道具检查`ListView`的渲染方法?

我遇到了与您 的问题已有一段时间,在查看了上述建议之后,我终于解决了问题。

事实证明(至少无论如何对我来说),我需要为要从renderSeparator方法返回的组件提供一个键(称为“键”的道具)。向我的renderRow或renderSectionHeader添加一个键没有做任何事情,但是将其添加到renderSeparator会使警告消失。

希望有帮助。

解决方法

我使用 ReactNative 为iOS和android构建了一个带有的应用ListView。当使用有效的数据源填充listview时,屏幕底部将显示以下警告:

警告:数组或迭代器中的每个子代都应具有唯一的“键”道具。检查的渲染方法ListView。

此警告的目的是什么?消息后,它们链接到此页面,在此讨论了完整的不同内容,这些内容与react native无关,而与基于Web的reactjs有关。

我的ListView是使用以下语句构建的:

render() { var store = this.props.store; return (<ListView dataSource={this.state.dataSource} renderHeader={this.renderHeader.bind(this)} renderRow={this.renderDetailItem.bind(this)} renderSeparator={this.renderSeparator.bind(this)} style={styles.listView} /> );}

我的数据源包含以下内容:

var detailItems = []; detailItems.push( new DetailItem(’plain’,store.address) ); detailItems.push( new DetailItem(’map’,’’) ); if(store.telefon) {detailItems.push( new DetailItem(’contact’,store.telefon,’Anrufen’,’fontawesome|phone’) ); } if(store.email) {detailItems.push( new DetailItem(’contact’,store.email,’Email’,’fontawesome|envelope’) ); } detailItems.push( new DetailItem(’moreInfo’,’’) ); this.setState({dataSource: this.state.dataSource.cloneWithRows(detailItems) });

并且ListView-Rows用以下内容呈现:

return ( <TouchableHighlight underlayColor=’#dddddd’><View style={styles.infoRow}> <Iconname={item.icon}size={30}color=’gray’style={styles.contactIcon}/> <View style={{ flex: 1}}><Text style={styles.headline}>{item.headline}</Text><Text style={styles.details}>{item.text}</Text> </View> <View style={styles.separator}/></View> </TouchableHighlight>);

一切正常,一切正常,除了警告似乎对我毫无意义。

向我的“ DetailItem”类添加密钥属性无法解决问题。

这是由于“ cloneWithRows”的结果真正传递给ListView的原因:

_dataBlob: I/ReactNativeJS( 1293): { s1: I/ReactNativeJS( 1293): [ { key: 2,I/ReactNativeJS( 1293): type: ’plain’,I/ReactNativeJS( 1293): text: ’xxxxxxxxxx’,I/ReactNativeJS( 1293): headline: ’’,I/ReactNativeJS( 1293): icon: ’’ },I/ReactNativeJS( 1293): { key: 3,type: ’map’,text: ’’,headline: ’’,icon: ’’ },I/ReactNativeJS( 1293): { key: 4,I/ReactNativeJS( 1293): type: ’contact’,I/ReactNativeJS( 1293): text: ’(xxxx) yyyyyy’,I/ReactNativeJS( 1293): headline: ’Anrufen’,I/ReactNativeJS( 1293): icon: ’fontawesome|phone’ },I/ReactNativeJS( 1293): { key: 5,I/ReactNativeJS( 1293): text: ’xxxxxxxxx@hotmail.com’,I/ReactNativeJS( 1293): headline: ’Email’,I/ReactNativeJS( 1293): icon: ’fontawesome|envelope’ },I/ReactNativeJS( 1293): { key: 6,type: ’moreInfo’,icon: ’’ } ] },

就像一个键一样,每个记录都有一个key属性。该警告仍然存在。

相关文章: