我正在尝试使用两种方式呈现数组数据:普通视图和 FlatList 。我了解到的是,我们在 map 和 renderItem 中传递了props
。
第一个块给出正确的输出:
const DATA = [
{id: '1',title: 'First Item'},
{id: '2',title: 'Second Item'},
]
const list = DATA.map((lst)=>{
return(<Text key={lst.id}>{lst.title}</Text>)
})
const Home=()=>{
return (<View><Text>{list}</Text></View>)
}
export default Home
在以下FlatList
组件中,它引发错误:
TypeError:TypeError:undefined is not an object(evaluating 'lst.title')
如果我将lst
更改为Item
,则显示正确的输出。 item
是renderItem中的预定义关键字吗?如果我将item
更改为其他任何单词,则会引发错误。
const DATA = [
{id: '1',title: 'First Item'},
{id: '2',title: 'Second Item'},
]
const Itm=({title})=>{
return (
<View>
<Text>{title}</Text>
</View>
);
}
const Home=()=>{
return (
<FlatList
data={DATA}
renderItem={({lst}) => <Itm title={lst.title} />}
keyExtractor={itm => itm.id}
/>
);
}
export default Home
答案 0 :(得分:0)
问题在于,在renderItem
中,您正在读取lst
关键字来破坏对象:
renderItem={({lst}) => <Itm title={lst.title} />} //Wrong
您正在尝试在没有该键的对象中读取属性lst
。
将({lst})
更改为(lst)
:
renderItem={(lst) => <Itm title={lst.title} />}
您可以在以下内容中了解有关对象分解的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
编辑。
看着FlatList react-native
Docs,Flatlist
返回的对象看起来像:
{item, index, separators}
item
是您需要呈现的项目。
所以您需要使用:
renderItem={({item }) => <Itm title={lst.title} />} //must be item
或
renderItem={({item: lst}) => <Itm title={lst.title} />}
答案 1 :(得分:0)
尝试删除{}
renderItem={({lst}) => <Itm title={lst.title} />}
它不需要写出知道它是析构函数的对象,而是尝试使用这种形状
renderItem={(lst) => <Itm title={lst.title} />}