[英]Accessing nested JSON object in React
Dataset: https://disease.sh/v3/covid-19/historical/usa?lastdays=all数据集: https://disease.sh/v3/covid-19/historical/usa?lastdays=all
I am newer to React and am trying to get my feet wet with a COVID-19 Tracker so bear with me... I am trying to access Timeline > Cases from the above dataset but can't seem to make it work.我是 React 的新手,正在尝试使用 COVID-19 跟踪器让我的脚湿透,所以请耐心等待...我正在尝试从上述数据集中访问时间轴 > 案例,但似乎无法使其工作。 I've tried
let date in data.timeline.cases
however that doesn't work either.我已经尝试
let date in data.timeline.cases
但这也不起作用。 Maybe i'm looking in the wrong spot - looking for some guidance.也许我在寻找错误的地方 - 寻找一些指导。 Thanks!
谢谢!
const buildChartData = (data, casesType) => {
let chartData = [];
let lastDataPoint;
for (let date in data.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data[casesType][date] - lastDataPoint,
}
chartData.push(newDataPoint);
}
lastDataPoint = data[casesType][date];
}
return chartData;
};
function LineGraph({ casesType = 'cases' }) {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async() => {
await fetch('https://disease.sh/v3/covid-19/historical/usa?lastdays=120')
.then((response) => {
return response.json()
})
.then(data => {
let chartData = buildChartData(data, casesType);
setData(chartData);
});
};
fetchData();
}, [casesType]);
Ok, as you said you tried with let date in data.timeline.cases
but you need to change the other part of code too.好的,正如您所说,您尝试
let date in data.timeline.cases
但您也需要更改代码的另一部分。
It s not data[casesType]
but data.timeline[casesType]
它不是
data[casesType]
而是data.timeline[casesType]
for (let date in data.timeline.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data.timeline[casesType][date] - lastDataPoint,
}
chartData.push(newDataPoint);
}
lastDataPoint = data.timeline[casesType][date];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.