我正在做一个简单的项目,使用 Google Books API 并遇到以下错误:无法读取未定义的属性“缩略图”。看起来,对于某些查询,没有图像或路径。例如,对于 books 查询,它工作正常并显示相关书籍。
据我所知,Google Books API 中没有适用于中小企业书籍的书籍封面,这就是它抛出错误的原因。我试图在 lodash 库的帮助下修复它,即 _set 函数。
document.querySelector('.search-book').addEventListener('click', getBook);
var titleHolder = document.querySelector('.title');
var columns = document.querySelector('.is-parent');
var total = '';
const apiKey = 'AIzaSyCu0GO52L8knIMQ7P_gmazBf_7wlngXqyc';
function getBook() {
var search = document.querySelector('#input').value;
console.log(search);
fetch(
`https://www.googleapis.com/books/v1/volumes?q=${search}:keyes&key=${apiKey}`
)
.then(function(res) {
return res.json();
})
.then(function(data) {
//console.log(data.items);
let items = data.items;
for (var i = 0; i < items.length; i++) {
// Volume info
let item = items[i].volumeInfo;
// Author
let author = item.authors;
// Image link
var imgLink = item.imageLinks.thumbnail;
// Title
let title = item.title;
// Description
let desc = item.description;
if (typeof desc === 'undefined') {
desc = 'No description available';
}
if (typeof author === 'undefined') {
author = 'No author';
}
if (!item.imageLinks.firstChild) {
_.set(
item,
'item.imageLinks',
'thumbnail:https://bulma.io/images/placeholders/128x128.png'
);
console.log(data);
}
total += `
<div class=" card tile is-child is-3 box">
<div class="card-image">
<figure class="image is-4by3">
<img src="${imgLink}" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<p class="title is-6 has-text-primary has-text-centered is-capitalized">${title}</p>
<p class="title is-6 has-text-primary has-text-centered is-capitalized">${author}</p>
<p class="has-text-black-ter has-text-weight-normal">${desc.slice(
0,
150
) + '...'}</p>
</div>
</div>
`;
console.log(item);
}
columns.innerHTML = total;
});
}
首先我检查对象中是否有缩略图属性,如果没有这样的属性,我使用 lodash _set 函数用占位符替换不存在的图像,但不起作用。请帮我解决这个问题。使用 loadsh 功能或建议我另一种出路。
if (!item.imageLinks.firstChild) {
_.set(
item,
'item.imageLinks',
'thumbnail:https://bulma.io/images/placeholders/128x128.png'
);
console.log(data);
}
最佳答案
我花了太多时间试图解决这个问题。
我就是这样做的,现在它终于没有抛出任何错误了
src={
book.volumeInfo.imageLinks === undefined
? ""
: `${book.volumeInfo.imageLinks.thumbnail}`
}
关于javascript - 谷歌图书 API : Cannot read property 'thumbnail' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51692323/