首页 > 解决方案 > React Native 读取 JSON 对象

问题描述

我有一个 JSON 请求,它返回一个 JSON 对象;

 {
  "kind": "youtube#searchListResponse",
  "etag": "zy8y9DkaOiYwKh0aStoEqOU_knU",
  "nextPageToken": "CBQQAA",
  "regionCode": "GB",
  "pageInfo": {
    "totalResults": 40,
    "resultsPerPage": 20
  },
  "items": [
    {
      "kind": "youtube#searchResult",
      "etag": "tvnouv0ap06XQKjt95dVECc_VZ4",
      "id": {
        "kind": "youtube#video",
        "videoId": "Qiyk-s60rgo"
      },
      "snippet": {
        "publishedAt": "2020-04-30T10:00:46Z",
        "channelId": "UCa_6KiOjxm6dEC_mMRP5lGA",
        "title": "Derby Futsal Club - Goal of the Season 2019/20 | Tom Gascoyne vs Birmingham",
        "description": "Derby Futsal Club's Goal of the Season as voted for by the public went to Tom Gascoyne for his goal against Birmingham in the National Futsal Series on 3rd ...",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/Qiyk-s60rgo/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/Qiyk-s60rgo/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/Qiyk-s60rgo/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "Derby Futsal",
        "liveBroadcastContent": "none",
        "publishTime": "2020-04-30T10:00:46Z"
      }
    },

我正在像这样阅读JSON;

useEffect(() => {
fetch(playertype(typeOfProfile))
  .then((response) => response.json())
  .then((json) => {
    setData(json)
    })
  .catch((error) => console.error(error))
  .finally(() => setLoading(false));
}, []);

return (
<View style={styles.body}>
  {isLoading ? <ActivityIndicator/> : (
    <FlatList
    data={data[0]}
      horizontal={true}
      keyExtractor={({ id }, index) => id}
      renderItem={({ item }) => (
        <View style={stylesB.container}>
          <Image style={styles.img} source={{ uri: chkValueI(item.items.snippet.medium.url) }} />
        </View>
      )}
    />
  )}
</View>
);
};

我正在将数据读取为 data[0],因此我点击了第一个对象,然后使用 item.items.snippet.medium.url 找到了我想要的属性(图像),但这不会返回任何内容。

我的问题是;

我可以使用 data[0] 指定我想要获取的对象,然后使用 item.items.snippet.medium.url 引用属性吗?

标签: javascriptjsonreact-native

解决方案


我可以使用 data[0] 指定我想要获取的对象,然后使用 item.items.snippet.medium.url 引用属性吗?

平面列表需要一个数据数组,因此您不需要一个平面列表来显示单个项目。您可以简单地使用 renderItem 函数并传递第一个项目。

item.items.snippet.medium.url

这里的 items 是一个数组,因此您应该使用类似下面的内容来访问该项目。在执行此操作之前最好检查数组长度。或者去地图来映射值。

item.items[0].snippet.medium.url

希望这可以帮助。


推荐阅读