[英]TypeError: Cannot read properties of undefined (reading 'map') when calling from an API
Im really stuck on a problem - if you run the code below you will get an error "TypeError: Cannot read properties of undefined (reading 'map') ".我真的遇到了一个问题——如果你运行下面的代码,你会得到一个错误“类型错误:无法读取未定义的属性(读取‘地图’)”。
When i console log out the "items" var I get 2 results as shown here:当我控制台注销“项目”变量时,我得到 2 个结果,如下所示:
The problem lies within the first result as it is empty.问题在于第一个结果,因为它是空的。 But can someone explain to me why this result is empty and why it produces 2 results?
但是有人可以向我解释为什么这个结果是空的,为什么它会产生 2 个结果?
This code was taken directly from here and modified to suit what is returned from the API.此代码直接取自此处并进行了修改以适应从 API 返回的内容。 Please consider running this code so you can see what i mean.
请考虑运行此代码,以便您了解我的意思。
import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
fetch("http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.dataseries.map(item => (
{console.log(item)}
))}
</ul>
);
}
}
export default App;
There are two mistakes which I could see我可以看到两个错误
dataseries
also you can't access property like that in an array right (because array have indexes by which we get the there value).dataseries
您也无法访问数组中那样的属性(因为数组具有索引,我们可以通过该索引获取那里的值)。 So what you could do is instead set this function to be like this所以你可以做的是把这个函数设置成这样
useEffect(() => {
fetch("http://www.7timer.info/bin/api.pllon=113.17&lat=23.09&product=astro&output=json")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result.dataseries);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)}, [])
And return function to be something like this并返回函数是这样的
return (
<ul>
{items.map(item => (
{console.log(item)}
))}
</ul>
);
Items is an array not the object eg [{...}, {...}] , desiredseries is inside object, not items.项目是一个数组而不是对象,例如 [{...}, {...}] ,desiredseries 在对象内部,而不是项目。
<ul>
{items.map(item => item.dataseries.map(ds=> (
{console.log(ds)}
)))}
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.