FlatList renderItem 错误,TypeError:未定义(评估‘item.id’)
2019-06-04
2117
我有一个 FlatList,我从数据库中放入了一些数据。 在 render 方法中,当我 console.log 时,state.data 会正确显示。但在 renderItem 方法中,我尝试打印 item 对象,但它没有显示,然后出现错误:
TypeError: undefined is not an object (evaluating 'item.id')
This error is located at:
in VirtualizedList (at FlatList.js:662)
in FlatList (at PlanView.js:49)
in RCTView (at View.js:44)
in TestLocalisation (at App.js:9)
in App (at withExpoRoot.js:22)
in RootErrorBoundary (at withExpoRoot.js:21)
in ExpoRootComponent (at renderApplication.js:34)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in AppContainer (at renderApplication.js:33)
我尝试用一些随机静态数据填充 flatlist 数据,它运行正常。
这是我的代码:
render() {
console.log("render => " + JSON.stringify(this.state.data));
return (
<View style={styles.container}>
<Button
style={styles.button}
onPress={this.addTraining}
title="ADD">
</Button>
<FlatList
data={this.state.data}
extraData={this.state}
renderItem={({ item }) =>
<View>
<Text>{item.name}</Text>
<Text>{item.sport}</Text>
<Text>{item.time}</Text>
<Text>{item.distance}</Text>
</View>}
keyExtractor={item => item.id}
/>
</View>
);
}
这是在 render 函数中记录的内容:
render => {
"_array":[
{"id":1,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":2,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":3,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":4,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":5,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":6,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":7,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":8,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":9,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":10,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":11,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":12,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":13,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":14,"name":"lol","sport":"running","time":120392,"distance":30}
],"length":14}
1个回答
问题出在提供给
renderItem
属性的函数中。该函数将针对数组的每个项目调用一次。
您的
renderItem
函数会解构它接收的对象并尝试读取键
item
的值。在它接收的对象中,没有键
item
,因此
item
将为
undefined
,并且
item.name
的访问将失败。
要解决此问题,您必须重构提供给
renderItem
的函数以正确解构该对象:
renderItem={({ name, sport, time, distance }) =>
<View>
<Text>{name}</Text>
<Text>{sport}</Text>
<Text>{time}</Text>
<Text>{distance}</Text>
</View>}
或者根本不使用解构:
renderItem={item =>
<View>
<Text>{item.name}</Text>
<Text>{item.sport}</Text>
<Text>{item.time}</Text>
<Text>{item.distance}</Text>
</View>}
请注意
const withDestrcuturingFn = ({ a, b, c }) => console.log(a)
和
const withoutDestrcuturingFn = (object_with_props_abc) => console.log(object_with_props_abc.a)
之间有关大括号的区别
Leo
2019-06-05