首页 > 解决方案 > 访问 api 子链接

问题描述

   componentDidMount = () => {
    fetch('https://api.teleport.org/api/urban_areas/?embed=ua:item/ua:images')
    .then(response => response.json())
    .then(data => {
      console.log(data)
      this.setState({
        images: data
      })
      console.log(this.state.images._embedded)
    })
  }

我目前是一名学生,正在从事一个从 api 读取数据并将其写入页面的项目。我正在尝试进入这个 api 的部分,在那里我可以获得一些图像的 url。以前,我只使用非常易于使用的 API,并且一直使用点表示法来获取数据及其内部和内部部分。到目前为止,我使用点符号“data._embedded”到达了“_embedded”部分。但我不知道如何进入说“ua:item”的那部分。我最终需要进入“移动”部分才能访问图片网址。顺便说一下,这是一个 React 项目,如果它对这个特定问题有任何影响的话。提前非常感谢!

在此处输入图像描述

标签: javascriptapifetch

解决方案


如果你有奇怪的东西作为 JSON 中的键值,你可以像这样使用方括号:

JSON.parse('{this:{is-a{JSON:"jsonstring"}}')["this"]["is-a"].JSON

产生:jsonstring

每当您得到只有一项的方括号(数组)时,索引为 0,您可以再次使用数组表示法:[0]

在你的情况下:

 componentDidMount = () => {
    fetch('https://api.teleport.org/api/urban_areas/?embed=ua:item/ua:images')
        .then(response => response.json())
        .then(data => {
          console.log(data)
          this.setState({
            images: data
          })
          console.log(this._embedded["ua:item"][0]. _embedded["ua:item"].photos[0].image.mobile)
        })
      }

推荐阅读