【问题标题】:Cannot render array elements using map in react native无法在本机反应中使用地图渲染数组元素
【发布时间】:2020-11-18 12:50:29
【问题描述】:

我有下面的react-native 代码,我使用这些代码使用map 呈现数组元素的文本。

import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import {Card} from 'react-native-elements';
import {View, Text} from 'react-native';


class Contact extends React.Component{
    constructor(props){
        super(props);
        this.state={
            arr:["Vipul","Satish","Manisha","Jonty"]
        }
    }
    render(){
        return(
            <Card>
                <Card.Title>Contact Information</Card.Title>
                <Card.Divider />
                <View>
                    {
                        this.state.arr.map(function(elem){
                            console.log(elem)
                            return(
                                <Text>Hello {elem}</Text>
                            );
                        })
                    }
                </View>
            </Card>
        );
    }
}

export default Contact;

我已经在我的类的构造函数中设置了带有状态的数组。首先我使用箭头函数返回&lt;Text&gt;。但它没有用。现在常规功能也不起作用。 我收到以下错误:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

但是,如果我用这个替换我的渲染函数:

render(){
   return(<View><Text>Hello world</Text></View>);
}

然后一切正常,我在屏幕上看到了 Hello world。另外,上面代码中的console.log 正确打印了所有数组元素,但只是没有渲染元素。

我已经检查了与此类似的其他主题,但无法获得任何帮助。

谢谢! 状态是这样的:

constructor(props){
        super(props);
        this.state={
            arr:["Vipul","Satish","Manisha","Jonty"]
        }
    }

编辑: 这是他们官方网站上给出的:

<Card>
  <Card.Title>CARD WITH DIVIDER</Card.Title>
  <Card.Divider/>
  {
    users.map((u, i) => {
      return (
        <View key={i} style={styles.user}>
          <Image
            style={styles.image}
            resizeMode="cover"
            source={{ uri: u.avatar }}
          />
          <Text style={styles.name}>{u.name}</Text>
        </View>
      );
    })
  }
</Card>

你可以看到我的代码和这个类似,所以它应该是这样工作的。

【问题讨论】:

  • 我 99% 确定问题出在您的状态结构中。请在此处发布。
  • 如果状态有问题,console.log 就不会打印元素。
  • 状态似乎是正确的。你能发帖&lt;Card /&gt;吗?我看到你渲染了Card,然后是Card.DividerCard.Title等等。怎么会这样?
  • 我在他们的官网上看到了。

标签: javascript reactjs react-native


【解决方案1】:

不确定您为 Card 使用的是什么库,但它可能需要 title 道具而不是字符串作为孩子。

【讨论】:

  • 我正在使用react-native-elements
  • 你展示了所有的代码吗?我怀疑问题出在没有显示的地方
  • 我必须说问题出在地图本身,因为正如我所说,如果我从渲染中删除所有内容并返回 hello world,它工作正常。
  • 查看react-native卡的官方文档:reactnativeelements.com/docs/card
  • 挠了挠头一个小时,发现问题出在&lt;Card.Title&gt;。我认为它应该将标题作为道具。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2021-09-26
  • 2022-12-11
  • 1970-01-01
相关资源
最近更新 更多