【问题标题】:How do I properly map array into <Text> (React native)如何正确地将数组映射到 <Text> (React native)
【发布时间】:2018-04-09 08:08:47
【问题描述】:

我有一个需要在&lt;Text&gt; 中映射的数组。这就是我在render()中得到的内容@

categories.map(category => <Text>{category.testHeader}</Text>

但它不打印任何东西。我猜&lt;Text&gt; 需要在render() 中,对吧?所以我尝试将它添加到要在render 中调用的函数中。像这样:

function myfunc() {
    return categories.map(category => <Text>{category.testHeader}</Text>)
}

然后在render():

<View>
    {myfunc()}
</View>

但是编译器说'无法读取未定义的属性'map'。 SO提示告诉我写:

function myfunc() {
    if (this.props.data) {
        return categories.map(category => <Text>{category.testHeader}</Text>)
    }
}

但是现在编译器告诉我data 是未定义的。不知道在这里做什么......:/

【问题讨论】:

  • 类别是全局变量吗?你的意思是 this.props.categories 还是 this.props.data.categories?
  • categories,它来自哪里?应该是props、local state、private variable等你是说this.props.data.categories

标签: arrays react-native


【解决方案1】:

你可以这样使用:

var categories = [{ id: 0, text: 'hasan' }, 
    { id: 1, text: 'erkan' },
    { id: 2, text: 'veli' }];

export default class App extends Component {
renderCategories() {
    return categories.map((item, index) => <Text key={index}>{item.text}</Text>);
}
render() {
    return (
        <View style={styles.container}>
            {this.renderCategories()}
        </View>
    );
}

}

【讨论】:

    【解决方案2】:

    首先将数据定义为[]。然后将类别数组分配给数据并尝试使用它。如果需要,请使用 JSON.parse(data)

    【讨论】:

      猜你喜欢
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多