使用hackernews api我试图使用我的响应对象获取属性“data”以将各个故事标题呈现给浏览器。最初,数据是一组代表个别故事的id。我发出第二个请求传递id以获取所有故事。截至目前,所有标题都迅速出现在浏览器的一行中。
class App extends Component {
constructor() {
super()
this.state = {
storyIds: null,
title: null
}
} // constructor end
componentDidMount () {
axios.get('https://hacker- news.firebaseio.com/v0/beststories.json?print=pretty')
// use arrow to access state
.then((res) => {
// res.data is array of story ids
this.setState({storyIds: res.data})
})
.then((res) => {
console.log(this.state.storyIds)
this.state.storyIds.map ((id) => {
axios.get(`https://hackernews.firebaseio.com/v0/item/${id}/title.json?print=pretty`)
.then((res) =>{
this.setState( {title: res.data})
console.log(res.data)
})
})
})
} // didMount end
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to Hackernews Top Stories</h2>
</div>
<p>{this.state.title}</p>
</div>
);
}
}
export default App;
如何使用地图循环我的response.data并在各行上生成标题?
答案 0 :(得分:0)
您需要在标题上使用.map函数并返回带标题的jsx元素。您还应该使用Promise.all()来解决所有ajax调用。
function storyTitles(titles) {
return titles.map(title => (
<p>{title}</p>
))
}
class App extends Component {
constructor() {
super()
this.state = {
storyIds: [],
titles: []
}
} // constructor end
componentDidMount () {
axios.get('https://hacker-news.firebaseio.com/v0/beststories.json?print=pretty')
.then((res) => {
this.setState({storyIds: res.data})
})
.then((res) => {
console.log(this.state.storyIds)
Promise.all(this.state.storyIds.map((id) => {
axios.get(`https://hackernews.firebaseio.com/v0/item/${id}/title.json?print=pretty`)
.then((res) => {
return Promise.resolve(res.data);
})
)
.then(responses => {
this.setState({titles: [...responses]})
})
})
})
} // didMount end
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to Hackernews Top Stories</h2>
</div>
{storyTitles(this.state.titles)}
</div>
);
}
}
export default App;