javascript ReactNative Flatlist - RenderItem 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48965635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReactNative Flatlist - RenderItem not working
提问by Corrado
So I'm trying to use React Native's FlatList renderItem property, but something very strange is happening.
所以我试图使用 React Native 的 FlatList renderItem 属性,但是发生了一些非常奇怪的事情。
The dataproperty is set to an array which has elements which are not undefined, but then, in the renderItemfunction, it gives me an error saying that the argument of the function is undefined, unless I call the argument item.
该data属性设置为一个数组,该数组具有未定义的元素,但是,在renderItem函数中,它给我一个错误,指出函数的参数未定义,除非我调用参数item。
Here's my code:
这是我的代码:
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>
)
}
}
If I swapped {item}with {userData}, then userDatawould be undefined later in the function. Does anyone know why this happens?
如果我换{item}用{userData},然后userData将后面的功能未定义。有谁知道为什么会这样?
回答by Prasun
Reason is that, every object in the dataarray is referenced through itemproperty of the actual parameter passed to renderItemfunction. Here, you are using object destructuringto extract only itemproperty 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 renderItemhere.
原因是,data数组中的每个对象都是通过item传递给renderItem函数的实际参数的属性来引用的。在这里,您使用对象解构来仅提取item传入对象的属性,这就是您使用{item}. 当您将此名称更改为userData(函数参数中缺少该名称)时,您将获得undefined. 看看renderItem这里的函数签名。
If you want to use userDatainstead of item, then you can rename itemto userDataas
如果你想使用userData,而不是item,然后可以重命名item,以userData作为
renderItem= ({item: userData}) => {...}
Hope this will help!
希望这会有所帮助!
回答by atulkhatri
Please read this answer carefully. I experienced it and wasted many hours to figure out why it was not re-rendering:
请仔细阅读此答案。我经历了它并浪费了很多时间来弄清楚为什么它没有重新渲染:
We need to set extraDataprop of FlatListif there is any change in the state like so:
如果状态有任何变化,我们需要设置extraDataprop,FlatList如下所示:
<FlatList data={this.state.data} extraData={this.state} .../>
Please see the official documentation here:
请在此处查看官方文档:
回答by Pravin Ghorle
I was missing a curlybraces { } around the item. After adding them , now it work fine.
我在项目周围缺少一个花括号 { }。添加它们后,现在它工作正常。
renderItem= {({item}) => this.Item(item.title)}

