背景
我正在React.js
应用中与{
"response": {
"items": [
{
"episode_id": 8528077,
"type": "RECORDED",
"title": "REPLICON RADIO 5-16",
"duration": 12741360,
"explicit": true,
"show_id": 1443546,
"author_id": 6168026,
"site_url": "https://www.spreaker.com/episode/8528077",
"image_url": "https://d1bm3dmew779uf.cloudfront.net/large/8f84530817540e259a824dea66fcf745.jpg",
"image_original_url": "https://d3wo5wojvuv7l.cloudfront.net/images.spreaker.com/original/8f84530817540e259a824dea66fcf745.jpg",
"published_at": "2016-05-16 23:00:05",
"download_enabled": true,
"waveform_url": "https://d3770qakewhkht.cloudfront.net/episode_8528077.gz.json"
}
],
"next_url": "https://api.spreaker.com/v2/shows/1443546/episodes?filter=listenable&last_id=8528077&limit=1"
}
}
进行API调用。返回响应但我在渲染函数中迭代数据时遇到问题。
Json回复
axios.get(`https://api.spreaker.com/v2/shows/1443546/episodes?filter=listenable&last_id=8589057&limit=1`)
.then(res => {
const episodes = res.data.response.items.map(r => r.data);
this.setState({episodes});
})
Axios获取方法
<ul>
{this.state.episodes.map(episode =>
<li key={episode.episode_id}>{episode.title}</li>
)}
</ul>
渲染功能
episode_id
问题
从文档中我相信我这样做是正确的,但我不断收到错误json
不存在。根据我的offest
,我将错误的数据呈现给视图?
答案 0 :(得分:1)
根据对象结构,您需要做的是:
const episodes = res.data.response.items;
this.setState({episodes});
或只是:
this.setState({episodes: res.data.response && res.data.response.items});
每个项目都没有data
属性...(r.data
)
答案 1 :(得分:1)
您需要在axios中执行的操作只需返回项目数组,然后在代码映射中对其进行渲染
axios.get(`https://api.spreaker.com/v2/shows/1443546/episodes?filter=listenable&last_id=8589057&limit=1`)
.then(res => {
const episodes = res.data.response.items;
this.setState({episodes});
})
当您使用map返回要保存到状态的值时,没有r.data
这样的值,这是非常不必要的。
并渲染为
<ul>
{this.state.episodes.map(episode =>
<li key={episode.episode_id}>{episode.title}</li>
)}
</ul>