如何在本机反应中一一显示数组中的元素

Posted

技术标签:

【中文标题】如何在本机反应中一一显示数组中的元素【英文标题】:How To show elements from array one By one in react native 【发布时间】:2021-11-22 19:35:58 【问题描述】:

我的 API 数据是这样的

"webimage":[],"appimage":[],"_id":"6155c2c77f31f9b79ba4273c","Categories":"Furniture","Subcategories":["Wooden Furniture","Office Furniture","Kitchen Furniture","Modular Office Furniture","Industrial Furniture","Steel Furniture","Living Room Furniture","|Storage and Display Furniture","Entryway Furniture","Inflatable Furniture","Patio Furniture & Accessories","Storage and Display Furniture"," Office & Commercial Furniture "]

我想渲染所有子类别但我无法渲染

T 试过这种方法,但它不起作用

val.Subcategories((item, key) => (
                  <Text key=key>item</Text>
                ))

【问题讨论】:

【参考方案1】:

这是有效的解决方案:Expo Snack

输出:

完整源代码:

import * as React from 'react';
import  Text, View, StyleSheet  from 'react-native';
import Constants from 'expo-constants';
import  Card  from 'react-native-paper';

const value = 
  webimage: [],
  appimage: [],
  _id: '6155c2c77f31f9b79ba4273c',
  Categories: 'Furniture',
  Subcategories: [
    'Wooden Furniture',
    'Office Furniture',
    'Kitchen Furniture',
    'Modular Office Furniture',
    'Industrial Furniture',
    'Steel Furniture',
    'Living Room Furniture',
    '|Storage and Display Furniture',
    'Entryway Furniture',
    'Inflatable Furniture',
    'Patio Furniture & Accessories',
    'Storage and Display Furniture',
    ' Office & Commercial Furniture ',
  ],
;

export default function App() 
  return (
    <View style=styles.container>
      value.Subcategories.map((item, index) => (
        <Card style= margin: 2, padding: 5 >
          <Text>item.trim()</Text>
        </Card>
      ))
    </View>
  );


const styles = StyleSheet.create(
  container: 
    flex: 1,
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  ,
);

【讨论】:

【参考方案2】:

好吧,你做错了,你应该像下面这样使用地图功能:

val.Subcategories.map((item, index) => (
    <Text key=`text-item-$index`>item</Text>
))

【讨论】:

以上是关于如何在本机反应中一一显示数组中的元素的主要内容,如果未能解决你的问题,请参考以下文章

从本地存储中一一检索数组列表

在反应jsx中一次遍历一个数组

从数组中一一获取元素并创建按钮

如何在 Swift 中一一显示 UITextField?

如何在本机反应中模拟上下文消费者反应元素

如何在本机反应中过滤对象数组?