如何使用map方法将查询参数传递给api,并将每个json响应连接到react中的setState



在下面的代码中,我通过map方法传递查询参数来调用api,我想连接每个查询的结果json并更新状态。

但在这里我面临的问题是,setState是用任何一个返回的json更新的。

import React from 'react';
const api_key = "key";
class card extends React.Component {
state = {
articles: [],
parameter: ['a', 'b', 'c', 'd', 'e']
};
componentDidMount = async () => {
this.state.newsPaper.map(async (querypara) => {
const requstone = await fetch(`https:someapisources=${querypara}&apiKey=${api_key}`);
const dataone = await requstone.json();
this.setState({
articles: dataone.articles
});
});
}
render() {
return (
<div>
<div>
{this.state.articles.map((article, index) => {
return (
<div key={index}>
<div>
<img src={article.urlToImage} alt="Avatar" />
<div>
<h4><b>{article.title}</b></h4>
<p>
{article.description}
</p>
<section>
<div>
<span>Source:</span>
<span>{article.source.name}</span>
</div>
</section>
</div>
</div>
</div>
)
})}
</div>
</div>
);
}
}
export default card;

我想添加每个响应json,并通过设置状态来渲染它。我该怎么做

下面是示例json响应。

{
"status": "ok",
"totalResults": 8,
"articles": [{
"source": {
"id": "recode",
"name": "Recode"
},
"author": "Recode Staff",
"title": "title",
"description": "Something",
"url": "url",
"urlToImage": "image url.jpg",
"publishedAt": "2018-11-26T13:23:06Z",
"content": "some content"
},
{
"source": {
"id": "recode",
"name": "Recode"
},
"author": "Recode Staff",
"title": "title",
"description": "Something",
"url": "url",
"urlToImage": "image url.jpg",
"publishedAt": "2018-11-26T13:23:06Z",
"content": "some content"
}
]
}

如果我正确理解您的问题,那么这里唯一需要的调整就是更新您的setState()逻辑,以便将响应中的articles附加到您状态下的articles数组:

this.state.newsPaper.map(async (querypara) => {
const requstone = await fetch(`https:someapisources=${querypara}&apiKey=${api_key}`);
const dataone = await requstone.json();
// Concatenate articles from response (dataone) to array in state
this.setState({
articles: this.state.articles.concat(dataone.articles)
});
}

最新更新