javascript 如何在react native中单独显示此Languages对象的标题?

hts6caw3  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(99)

我的目标是在react native中显示这些对象的所有标题。

{
    "Languages": [
        {
            "PKM": "Languages",
            "Title": "Tamil2",
        },
        {
            "PKM": "Languages",
            "Title": "தமிழ்",
        },
        {
            "PKM": "Languages",
            "Title": "English",
        }
    ],
    "status": "success",
    "message": "Retrieve Success!"
}

预期的结果是从这些对象中单独显示三个标题。我见过使用js parse方法,但它只显示单个标题,而不是三个。

iqjalb3h

iqjalb3h1#

使用Map

const data = {
  Languages: [
    {
      PKM: 'Languages',
      Title: 'Tamil2',
    },
    {
      PKM: 'Languages',
      Title: 'தமிழ்',
    },
    {
      PKM: 'Languages',
      Title: 'English',
    },
  ],
  status: 'success',
  message: 'Retrieve Success!',
};

渲染时

{data.Languages.map((item) => (
  <Text>{item.Title}</Text>
))}

更新码

import React, { useEffect, useState } from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';

const data = {
  Languages: [
    {
      PKM: 'Languages',
      Title: 'Tamil2',
    },
    {
      PKM: 'Languages',
      Title: 'தமிழ்',
    },
    {
      PKM: 'Languages',
      Title: 'English',
    },
  ],
  status: 'success',
  message: 'Retrieve Success!',
};

export default function App() {
  // const [data, setData] = useState([]);

  // useEffect(() => {
  //   fetch('https://dummyjson.com/products/1')
  //     .then((res) => res.json())
  //     .then((json) => {
  //       console.log(json);
  //       setData(json.Languages);
  //     });
  // });
  const renderItem = (item) => {
    return <Text>{item.item['Title']}</Text>;
  };
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        Change code in the editor and watch it change on your phone! Save to get
        a shareable url.
      </Text>
      <FlatList
        style={{ flex: 1 }}
        data={data['Languages']}
        renderItem={renderItem}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

相关问题