React native FlatList renderItem错误,TypeError:未定义(正在评估';item.id';)
我有一个平面列表,我把一些数据从我的数据库。 在render方法中,当I console.log时,state.data会正确显示。但是在renderItem方法中,我尝试打印item对象,但它没有显示,然后出现错误:React native FlatList renderItem错误,TypeError:未定义(正在评估';item.id';),react-native,react-native-flatlist,React Native,React Native Flatlist,我有一个平面列表,我把一些数据从我的数据库。 在render方法中,当I 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
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)
我试着用一些随机的静态数据填充平面列表数据,它工作得非常好
这是我的代码:
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>
);
}
问题出在提供给
renderItem
prop的函数中。该函数将为数组的每个项调用一次
您的renderItem
函数将分解它接收的对象,并尝试读取键项的值。在它接收的对象中没有键项
,因此项
将是未定义的
,访问项。名称
将失败
要解决此问题,您必须重构提供给renderItem
的函数,以正确解构该对象:
renderItem={({ name, sport, time, distance }) =>
<View>
<Text>{name}</Text>
<Text>{sport}</Text>
<Text>{time}</Text>
<Text>{distance}</Text>
</View>}
及
问题出在提供给renderItem
prop的函数中。该函数将为数组的每个项调用一次
您的renderItem
函数将分解它接收的对象,并尝试读取键项的值。在它接收的对象中没有键项
,因此项
将是未定义的
,访问项。名称
将失败
要解决此问题,您必须重构提供给renderItem
的函数,以正确解构该对象:
renderItem={({ name, sport, time, distance }) =>
<View>
<Text>{name}</Text>
<Text>{sport}</Text>
<Text>{time}</Text>
<Text>{distance}</Text>
</View>}
及
为什么官方文件没有解释这一点-(这是不正确的,不管是否被破坏。OP变异数组并获取undefiend@MedetTleukabiluly请重新阅读答案…为什么官方文档中没有解释这一点?:-(这是不正确的,不管是否被破坏。OP变异数组并获取undefiend@MedetTleukabiluly请重读答案。。。
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)