我正在React Hooks项目上使用访存调用标准JSON文件。 (我正在模拟使用JSON-Server的服务器来读取本地json文件)
在我的主要函数中,我正在调用一个变量和一个函数,就像任何普通的React Hook一样,并将其设置为空数组,因为我正在使用访存来调用API数据。
let [items, setItems] = useState([]);
然后,我要对模拟服务器进行实际的提取调用
const fetchItems = async () => {
const url = "http://localhost:3002/learn";
const response = await fetch(url);
items = await response.json();
setItems(items);
console.log(items[0].title);
}
The console.log(items[0].title)
does in fact return the correct value.
如果我想显示所有结果,以下方法甚至可以工作。
{items.map((item) =>
<img src={item.source} alt={item.title} title={item.title} className="img-fluid mx-auto d-block" />
)}
However, once I want to display a single value in my return, I get an error message saying:
"TypeError: Cannot read property 'source' of undefined"
The code that I'm using, just to test at first is the same exact thing as my console.log
from before.
<img src={items[0].source} alt={items[0].title} title={items[0].title} className="img-fluid mx-auto d-block" />
我是否错过了一个重要的步骤,该步骤使我可以在返回时使用获取的信息?
If I were to hard-code my JSON data on the same component, it would work. I feel like it has something to do with fetch. I was looking at this question, and it's similar, but not the same thing. I'm also using hooks and also not axios. Can't display data after fetch
更新: JSON文件如下所示:
{
"learn": [
{
"id": 1,
"title": "Angular JS",
"source": "./images/logo-angular-js.png"
},
{
"id": 2,
"title": "Firebase",
"source": "./images/logo-firebase.png"
},
{
"id": 3,
"title": "GraphQL",
"source": "./images/logo-graphql.png"
}
]
}
On your first render,
items
has a length of 0, soitems[0]
is going to beundefined
. You're likely trying to render before that first item has loaded.Check if
items[0]
is defined before trying to accessitems[0].source
and the like.On the first render, this will cause nothing to be output. After the
setItems
call is made, the component will re-render, and this time (if there were items being set), it'll render your item.