ReactNative Flatlist-RenderItem不起作用 [英] ReactNative Flatlist - RenderItem not working
问题描述
所以我试图使用React Native的FlatList renderItem属性,但是正在发生一些非常奇怪的事情.
So I'm trying to use React Native's FlatList renderItem property, but something very strange is happening.
data
属性设置为一个数组,该数组具有未定义的元素,但是在 renderItem
函数中,它给我一个错误,指出该参数函数的定义是不确定的,除非我调用参数 item
.
The data
property is set to an array which has elements which are not undefined, but then, in the renderItem
function, it gives me an error saying that the argument of the function is undefined, unless I call the argument item
.
这是我的代码:
export default class Profile extends React.Component {
onLearnMore = (user) => {
this.props.navigation.navigate('UserDetail', user)
}
render() {
return (
<List>
<FlatList
data={data.users}
renderItem={( {item} ) => {
console.log(item)
return (<ListItem
roundAvatar
title={`${item.fName} ${item.lName}`}
onPress={() => this.onLearnMore(item)}
/>)
}}
/>
</List>
)
}
}
如果我将 {item}
与 {userData}
交换,则 userData
在该函数的后面将是未定义的.有人知道为什么会这样吗?
If I swapped {item}
with {userData}
, then userData
would be undefined later in the function. Does anyone know why this happens?
推荐答案
原因是,通过实际参数的 item
属性引用了 data
数组中的每个对象传递给 renderItem
函数.在这里,您使用对象解构仅提取项目传入对象的code>属性,这就是为什么您使用
{item}
.当您将此名称更改为 userData
(函数参数中缺少该名称)时,您将得到 undefined
.看看 renderItem
的功能签名此处.
Reason is that, every object in the data
array is referenced through item
property of the actual parameter passed to renderItem
function. Here, you are using object destructuring to extract only item
property of the passed in object, thats why u are using {item}
. When you are changing this name to userData
(which is missing in the function argument), you are getting undefined
. Have a look at the function signature of renderItem
here.
如果要使用 userData
而不是 item
,则可以将 item
重命名为 userData
作为
If you want to use userData
instead of item
, then you can rename item
to userData
as
renderItem= ({item: userData}) => {...}
希望这会有所帮助!
这篇关于ReactNative Flatlist-RenderItem不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!