如何在 React Native 中使用 Map 函数。未定义不是一个函数(靠近"...this.props.route.params.data.map...')



我是新手。我通过Params从第一屏幕发送数据到第二屏幕。在第一个屏幕上,我从API服务器获得数据。现在我想在第二个屏幕中显示这些数据。我有多个数据,所以我想只显示一次,然后之后。例如100个数据,那么100张卡应该自动创建。

但现在我得到这样的错误=>Undefined不是一个函数(在'…this.props.route. parms .data.map…'附近)

这是我的代码

<View>
//  {/*Use map on data as you want to show*/}
{this.props.route.params.data.map(item => 
<View style={{alignItems:"center", justifyContent:"center",height:140, width:"90%", marginTop:30}}>

<TouchableOpacity onPress={() => navigation.navigate("FormItems")}>
<Card center middle shadow style={{ height:80, width:"100%" }} >
{/*Use item*/}
<Text medium height={15} size={14}style={{ fontWeight: "bold", paddingRight:190}}>  
{item} 
</Text>

</Card>
</TouchableOpacity>
</View>
)}
</View>

要解决这个问题,你必须这样写代码:

{this.props.route.params && this.props.route.params.data && 
this.props.route.params.data.map((item,index) => {
return(
<View></View>
)) 

可以使用可选链接检查数据是否在route.params中。

完整代码:

import React, { Component } from "react";
import { Text, View } from "react-native";

export default class App extends Component {
render() {
const data = this.props?.route?.params?.data;
return (
<View>
{data &&
data.map((item, index) => {
return (
<View
style={{
alignItems: "center",
justifyContent: "center",
height: 140,
width: "90%",
marginTop: 30,
}}
>
<TouchableOpacity
onPress={() => navigation.navigate("FormItems")}
>
<Card
center
middle
shadow
style={{ height: 80, width: "100%" }}
>
{/*Use item*/}

<Text
medium
height={15}
size={14}
style={{ fontWeight: "bold", paddingRight: 190 }}
>
{item}
</Text>
</Card>
</TouchableOpacity>
</View>
);
})}
</View>
);
}
}

相关内容

最新更新