本文主要是介绍RN在使用FlatList时报错missing key for items...,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码:
import React, { Component } from 'react'//imr
import { FlatList, Text, StyleSheet } from 'react-native'//imrnexport default class flatlist extends Component {constructor(props){super(props);this.state = {data:[{name:'fan'},{name:'chen'},{name:'liu'},{name:'kan'}]}}render() {return (<FlatListdata={this.state.data}renderItem={({item})=><Text>{item.name}</Text>}style={styles.container}/> );}
}
const styles = StyleSheet.create({container:{flex:1,marginTop: 200,alignSelf: 'center',}
})
报错:
由于默认情况下,flatlist会查找data中属性为key的值,而我们需要它查找的是name属性,这就需要通过keyExtractor属性来指定使用 name作为列表每一项的 key,然后再对其进行引用,如下:
加上:
_keyExtractor = (item, index) => item.name; //keyExtractor属性指定使用 id 作为列表每一项的 key..........keyExtractor = { this._keyExtractor }
完整代码:
import React, { Component } from 'react'//imr
import { FlatList, Text, StyleSheet } from 'react-native'//imrnexport default class flatlist extends Component {constructor(props){super(props);this.state = {data:[{name:'fan'},{name:'chen'},{name:'liu'},{name:'kan'}]}}_keyExtractor = (item, index) => item.name;render() {return (<FlatListdata={this.state.data}keyExtractor = { this._keyExtractor }renderItem={({item})=><Text>{item.name}</Text>}style={styles.container}/> );}
}
const styles = StyleSheet.create({container:{flex:1,marginTop: 200,alignSelf: 'center',}
})
这篇关于RN在使用FlatList时报错missing key for items...的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!