我正在尝试根据backgroundImage
的值动态选择item.imageLinks.smallThumbnail
。
如果我的API返回的数组具有一个smallThumbnail
URL,那么我想将其用作backgroundImage
或在{{内使用backgroundImage
的本地默认book.png
1}}。
下面是我的代码,但是当../public
为item.imageLinks.smallThumbnail
且不使用备用undefined
时却无法使用,但出现错误:
book.png
请帮助。
谢谢
Type Eror: Cannot Read 'smallThumbnail of undefined
答案 0 :(得分:1)
在您的代码中,您需要处理未定义item.imageLinks
的情况,因此问题在于以下行:
`url({${item.imageLinks.smallThumbnail} || ../public/book.png })`
如果未定义imageLinks
,则该行将出错。
相反,您可以像这样使用三元运算符:
`url({${(item && item.imageLinks && item.imageLinks.smallThumbnail) ? item.imageLinks.smallThumbnail : `../public/book.png`} })`
尽管很难阅读。
我会考虑对其进行重构,以便在render方法的顶部具有一组对象,在其中存储每个项目的图像和图像url,然后在render方法中对其进行迭代。
答案 1 :(得分:1)
如果 imageLinks 是未定义,则它不是对象,因此您将无法使用点语法,因此尝试获取 smallThumbnail时出错属性。
尝试以下方法:
<div
className="book-cover"
style={{
width: 128,
height: 193,
backgroundImage: `url(${(item.imageLinks && item.imageLinks.smallThumbnail) || "../public/book.png"})`
}}
></div>
...,因此您首先要检查图像链接。
答案 2 :(得分:1)
由于您的imageLinks
本身不是属性,因此可以这样处理:
let imageUrl = item.imageLinks ? item.imageLinks.smallThumbnail : '../public/book.png';
return(
<ol className="books-grid">
{book.map( (item) => (
<li key={item.id}>
<div className="book">
{item.shelf && (
<div className="book-top">
<div
className="book-cover"
style={{ width: 128, height: 193, backgroundImage: `url(${imageUrl})` }}></div>
答案 3 :(得分:0)
This is now solved, Below is the code that worked.
return(
<ol className="books-grid">
{book.map( (item) => (
<li key={item.id}>
<div className="book">
{item.shelf && (
<div className="book-top">
<div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url(${(item.imageLinks && item.imageLinks.smallThumbnail) || "book.jpg"})` }}></div>
我在这里学到的一个技巧是使用&&检查未定义的内容,否则JS会报错。 谢谢大家
答案 4 :(得分:0)
这是一个示例,如果您使用的是react js
从'react'导入React,{Component,Fragment} 从“ react-router-dom”导入{Link}
const Post =(数据)=> { 返回(
<div
style={{
backgroundImage: `linear-gradient(
325deg,
rgba(0, 36, 51, 1) 0%,
rgba(98, 218, 255, 0.164) 100%
),url(${(data.img)})`
}} className="cardService">
<div>
<h1 className='serviceTitle'>{data.name}</h1>
<h6 className='serviceDescription'>{data.description}</h6>
</div>
</div>
</Fragment>
)
}
导出默认帖子;