【发布时间】:2020-06-04 22:59:47
【问题描述】:
我正在尝试从此 api 访问数据。当它像以下格式时,我知道如何访问它的数据
{
"confirmed": {
"value": 6429453,
"detail": "https://covid19.mathdro.id/api/confirmed"
},
"recovered": {
"value": 2804649,
"detail": "https://covid19.mathdro.id/api/recovered"
},
"deaths": {
"value": 385873,
"detail": "https://covid19.mathdro.id/api/deaths"
},
我会这样做
try {
const {/* data: {confirmed, recovered, deaths, lastUpdate}} = await axios.get(url); */
data: { confirmed, recovered, deaths, lastUpdate },
} = await axios.get(changeableUrl);
const modifiedData = {
confirmed,
recovered,
deaths,
lastUpdate
};
return modifiedData;
/* return response; */
} catch (error) {
console.log(error);
}
};
但是当我试图访问统计数据所在的数据时,它不起作用,它是 嵌套 json 对象,
[
{
"country": "US",
"province": "Louisiana",
"county": "Acadia",
"updatedAt": "2020-06-03 02:33:13",
**"stats": {
"confirmed": 428,
"deaths": 24,
"recovered": 0
},**
"coordinates": {
"latitude": "30.2950649",
"longitude": "-92.41419698"
}
}
]
我尝试以下方法:
if (county) {
changeableUrl = `${url}/jhucsse/counties/${county}`;
try{
const {data:{updatedAt, stats:{confirmed, deaths, recovered}}} = await axios.get(changeableUrl);
const modifiedData = {
cases: confirmed,
deaths,
recovered,
updated: updatedAt
}
console.log(modifiedData);
return modifiedData;
}catch(error){
console.log(error);
}
}
有没有更好的方法来访问 api 数据?提前谢谢!
编辑: CodeSandbox 链接在这里:https://codesandbox.io/s/pickers-l6mip?file=/src/component/statepicker.jsx
更新工作代码:
if (county) {
try {
const { data } = await axios.get(`${url}/jhucsse/counties/${county}`);
const modifiedData = {
cases: data[0].stats.confirmed,
recovered: data[0].stats.recovered,
deaths: data[0].stats.deaths
};
【问题讨论】:
-
我已经多次阅读您的问题,但我真的很难理解您在问什么。您是否获得了预期的数据?这个问题是关于如何使用解构重新格式化数据?来自 api 调用的原始响应数据是什么样的?
-
如果您显示完整内容,json 看起来格式不正确
-
@Xesenix 这是一个链接,指向它在网页ibb.co/kg8d4fN控制台中的显示方式,谢谢!如果需要进一步说明,请告诉我!
-
data 是一个对象数组,而不是您尝试从中解构 stats 属性的对象
-
@SethLutske 谢谢,很抱歉造成混乱,我无法取回数据,因为我不知道如何访问“统计数据”的数据。我可以使用 const {data} = await axios.get(
${url}/jhucsse/counties/${county}); 访问完整数据;我还可以使用以下代码获取国家/地区 County updatedAt 信息 const modifiedData = data.map((fetchedCounty) => ({ country: fetchedCounty.country, County: fetchedCounty.county })) 但我就是无法获得从“统计”中确认恢复等谢谢您的回答!
标签: reactjs