[英]TypeError: Cannot read property 'url' of undefined react strapi in JSON object
I'm using strapi with react.我正在使用带有反应的strapi。 I'm fetching a JSON object (home).
我正在取一个 JSON object(家)。 If I do
console.log(home)
I get:如果我做
console.log(home)
我得到:
{
"id": 6,
"created_at": "2020-06-21T07:07:36.000Z",
"updated_at": "2020-06-21T07:18:40.000Z",
"HomeTextTop": "Home text here.",
"HomeTitle": "Home title here",
"Hero": {
"id": 3,
"name": "facade_pastel_summer_123664_800x600",
"alternativeText": "",
"caption": "",
"width": 800,
"height": 600,
"url": "http://someurlhere.com"
}
}
If I console.log(home.Hero)
I get the appropriate:如果我
console.log(home.Hero)
我得到适当的:
{
"id": 3,
"name": "facade_pastel_summer_123664_800x600",
"alternativeText": "",
"caption": "",
"width": 800,
"height": 600,
"url": "http://someurlhere.com"
}
However, if I drill down and try and get just the URL console.log(home.Hero.url)
I get this error:但是,如果我向下钻取并尝试仅获取 URL
console.log(home.Hero.url)
我会收到此错误:
TypeError: Cannot read property 'url' of undefined react strapi in JSON object
What am I missing here?我在这里想念什么?
The 'action' fetching code is: 'action' 获取代码是:
export const fetchHome = () => {
return dispatch => {
dispatch(fetchHomeBegin())
return fetch(`${strapiUrl}/home`, {
method: 'get',
mode: 'cors',
headers: { 'Content-Type': 'application/json' }
})
.then(res => res.json())
.then(json => {
console.log(json)
dispatch(fetchHomeSuccess(json))
})
.catch(error => dispatch(fetchHomeFail(error)))
}}
And JSON.stringify(home.Hero)
gives the same result in string form并且
JSON.stringify(home.Hero)
以字符串形式给出相同的结果
Here's what's happening.这是正在发生的事情。
This is likely because at the moment of reading url from Hero, Hero is not yet defined (as the error message suggests).
这可能是因为在从 Hero 读取 url 时,尚未定义 Hero(如错误消息所示)。 You could tackle this by first confirming Hero is defined before reading url.
您可以通过在阅读 url 之前首先确认 Hero 已定义来解决此问题。 Something like this: console.log(home.Hero && home.Hero.url).
像这样:console.log(home.Hero && home.Hero.url)。
Though this leads to a lot of cumbersome code, and therefor (imo) it would be better to use https://www.npmjs.com/package/immutable to manage the data that is returned from the Strapi api.
尽管这会导致大量繁琐的代码,因此(imo)最好使用https://www.npmjs.com/package/immutable来管理从 Strapi api 返回的数据。
You would then set home as an immutable object (a Map) and read url like this: console.log(home.getIn(['Hero', 'url']). If Hero is undefined here your application will not crash, but instead false will be returned. - Boaz Poolman - slack.strapi
然后,您可以将 home 设置为不可变的 object(地图)并读取 url,如下所示:console.log(home.getIn(['Hero', 'url'])。而是返回 false。- Boaz Poolman - slack.strapi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.