[英]reactJS fetch json data from API
我是JS和reactJS的新人。 我想从 API 获取信息到数组。 我制作了 API,它显示了我数据库中的所有信息。 它看起来像这样:
const [tempNew, setTempNew] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather')
.then(response => {
return response.json();
})
.then((jsonData) => {
let tmpArray = [];
for (var i = 0; i < jsonData.length; i++) {
tmpArray.push(jsonData.dayCelsius[i]) <---- here is the error
}
setTempNew(tmpArray);
})
}
我想将“dayCelsius”行中的所有值收集到数组中。
我需要在此代码中更改什么? 谢谢:)
您可以使用map
function 返回每个元素的dayCelsius
值并将它们存储在tmpArray
中。
let tmpArray = jsonData.map((el, i) => el.dayCelsius);
您能否提供有关该错误的更多信息? 但是您可以尝试使用 map function 之类的
const tmpArray = jsonData.map(r => r.dayCelsius);
因此,我的理解是,您很难从从 API 获取的对象数组中获取dayCelsius
值。
很难弄清楚问题是什么,因为需要更多有关错误的信息才能查看问题所在。
我在这里所做的不同之处是我使用data.map((r,e) => r.dayCelsius)
而不是 for-loop 和jsonData.dayCelsius[i]
。
const [temp, setTemp] = useState([]); const getAllWeatherCelsius = () => { fetch('http://localhost:5000/weather', { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", } }).then(response => { return response.json(); }).then((data) => { const tempArray = data.map((r,e) => r.dayCelsius); setTemp(tempArray); }).catch(err => console.log(err)); }
希望对你有帮助,祝你有个美好的一天:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.