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

时间:2021-02-19 08:48:14

标签: react-native

我是本机反应的新手。我已经通过 Params 将数据从第一个屏幕发送到第二个屏幕。在第一个屏幕中,我从 API 服务器获取数据。现在我想在第二个屏幕中显示该数据。我有多个数据,所以我只想显示一次,然后在 .例如100个数据会来然后100张卡片应该自动创建。

但现在我收到这样的错误 => undefined 不是函数(靠近 '...this.props.route.params.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>

2 个答案:

答案 0 :(得分:0)

要解决您的问题,您必须像这样编写代码:

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

答案 1 :(得分:0)

您可以使用可选链来检查数据是否在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>
        );
      }
    }