在 React 中访问地图对象数组中的数据

Accessing data in an array of object for a map in React

"data": {
 "offset": 0,
 "limit": 20,
 "total": 1,
 "count": 1,
 "results": [
   {
    "id": 1009144,
    "name": "A.I.M.",
    "modified": "2013-10-17T14:41:30-0400",
    "thumbnail": {
      "path": "i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec",
      "extension": "jpg"
    },
    "resourceURI": "gateway.marvel.com/v1/public/characters/1009144",
    "comics": {
      "available": 33,
      "collectionURI": "gateway.marvel.com/v1/public/characters/1009144/comics",
      "items": [
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/36763",
          "name": "Ant-Man & the Wasp (2010) #3"
        },
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/17553",
          "name": "Avengers (1998) #67"
        }
     ]
   }
  }
]
}

我正在使用 axios 从 React 组件内的 api 获取数据。我想访问我的 json 响应中的关键项以设置状态,但我不能。

export default class Hero extends React.Component {
constructor(props) {
super(props);
this.state = {
    details : [],
    comics :[]
};
}
componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({details : res.data.data.results,
                    comics : res.data.data.results.results[6].items});
})
}
render() {  

     (<div>
      </div>)
}   
}

我可以访问我的状态详细信息,但不能访问漫画状态的详细信息。

结果数组只包含一项,因此您需要使用索引 0 而不是 6。另一件事是 items 存在于 comics 中,所以首先访问 comics 然后访问 items,使用这个:

componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({
            details : res.data.data.results,
            comics : res.data.data.results[0].comics.items});
     })
}

运行 这个片段:

let data = {"data": {
 "offset": 0,
 "limit": 20,
 "total": 1,
 "count": 1,
 "results": [
   {
    "id": 1009144,
    "name": "A.I.M.",
    "modified": "2013-10-17T14:41:30-0400",
    "thumbnail": {
      "path": "i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec",
      "extension": "jpg"
    },
    "resourceURI": "gateway.marvel.com/v1/public/characters/1009144",
    "comics": {
      "available": 33,
      "collectionURI": "gateway.marvel.com/v1/public/characters/1009144/comics",
      "items": [
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/36763",
          "name": "Ant-Man & the Wasp (2010) #3"
        },
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/17553",
          "name": "Avengers (1998) #67"
        }
     ]
   }
  }
 ]
 }
}
console.log('items', data.data.results[0].comics.items)

items 出现在 comics 中不是结果数组中的 6th 项,而是结果数组 first object 中的 6th 项因此你需要像访问它一样。

res.data.data.results[0].comics.items

将 componentDidMount 函数更改为

componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({details : res.data.data.results,
                    comics : res.data.data.results[0].items});
    })
}