【问题标题】:Read Json data that have nested array in react native在 React Native 中读取具有嵌套数组的 Json 数据
【发布时间】:2023-01-14 07:44:07
【问题描述】:

我有 Json 数据,想使用 Native Base 读取流派数据,特别是名称键。这是我的 Json,我是从 TMDB API 得到的

流派键使用嵌套数组存储数据

"genres": [
    {
      "id": 878,
      "name": "Science Fiction"
    },
    {
      "id": 12,
      "name": "Adventure"
    },
    {
      "id": 28,
      "name": "Action"
    }
  ],

我正在尝试像这样从 API 加载数据

fetchDetails = () => {
    fetch(
      `https://api.themoviedb.org/3/movie/${movie_id}?api_key=9b68fedd9d8cacc97e967403feb9d5fc`
    )
      .then((response) => response.json())
      .then((json) =>
        this.setState({
          contentGenre: json.genres[0]
        })
      )
      .catch((error) => console.error(error))
      .finally(() =>
        this.setState({
          isCategoriesLoading: false,
        })
      );
  };

我正在尝试像这样显示流派,但没有显示数据

<Text>{contentGenre.name}</Text>

谢谢你的帮助!

【问题讨论】:

  • 你能分享你的完整组件吗?
  • 你能粘贴你从api响应中得到的整个json吗

标签: json react-native multidimensional-array


【解决方案1】:

不太确定是什么问题。以下代码可以在控制台上运行并打印 Drama。我为电影 ID 使用了固定值 (345)。也许您应该从问题中删除您的 API 密钥。

拿来( https://api.themoviedb.org/3/movie/345?api_key=9b68fedd9d8cacc97e967403feb9d5fc ) .then((response) => response.json()) .then((json) =>( console.log(json.genres[0].name) ) ) .catch((error) => console.error(error)) .finally(() => console.log("完成") );

【讨论】:

  • 也许您测试的 movie_id 没有返回有效值并且那里没有类型?
【解决方案2】:

以下是如何访问第一个流派的名称。

fetch(`https://api.themoviedb.org/3/movie/${movie_id}?api_key=...`)
  .then((response) => response.json())
  .then((json) => json["genres"][0].name)
  .then(console.log)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多