我有一个简单的json api,想显示一些具有react的对象字段。该api具有以下结构:
{"data" : [
0: Object
id: "1"
type: "Item"
attributes: Object
title: "lorem impsum"
body: "lorem ipsum"
1: Object
id: "2"
....
]}
我正在尝试显示属性项目(标题,正文)
问题是
这可以正常工作并显示id
{items.map(item =>
<div>{item.id}</div>
)}
但
如果我尝试使用,{item.attributes.title}
我会收到
TypeError: Cannot read property 'title' of undefined
因此item.attributes
是未定义的。
怎么了
这是最常见的错误,因为您永远不知道将从服务器获取什么对象,因此,这始终是在访问数据之前进行检查的好方法,因此您可以尝试
{item.attributes && item.attributes.title ? item.attributes.title : 'print something for missing title' }
//item.attributes && item.attributes.title means if both the values are present in Object
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句