搜索为空字符串或与 API 调用不匹配



如果搜索是空字符串或无法从 API 中找到输入字段中值的任何匹配项,如何捕获并打印给用户的消息。

// show the search results from user input
const searchTvShows = ({ target }) => {
fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`)
.then(blob => blob.json())
.then(shows => {
const app = document.getElementById('app');
app.innerHTML = shows.map(({ show }) => `
<div class="col-sm movie-content">
<div class="movie-image">
${show.image ? `<img src="${show.image.medium}">` : `<img class="fallbackImage"src="design/icons/No_image_available.svg">`}
</div>
<div class="movie-info">
<h1>${show.name}</h1>
</div>
</div>
`).join(' ');
})
}

我刚刚检查过,当成功搜索不匹配时,您的 API 会返回一个空数组,因此:

if (shows.length) {
// do what you're doing
} else {
// show a message saying there were no matches
}

在上下文中,还要处理我在评论中提到的问题:

const searchTvShows = ({ target }) => {
fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`)
.then(response => {
if (!response.ok) {
throw new Error();
}
return response;
})
.then(blob => blob.json())
.then(shows => {
const app = document.getElementById('app');
if (shows.length) {
app.innerHTML = shows.map(({ show }) => `
<div class="col-sm movie-content">
<div class="movie-image">
${show.image ? `<img src="${show.image.medium}">` : `<img class="fallbackImage"src="design/icons/No_image_available.svg">`}
</div>
<div class="movie-info">
<h1>${show.name}</h1>
</div>
</div>
`).join(' ');
} else {
app.innerHTML = "<em>No matching shows</em>";
}
})
.catch(err => {
// Report the error or similar
})
}

如果这对您很重要(对某些人来说似乎很重要(,您可以使用||来避免if/else

const searchTvShows = ({ target }) => {
fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`)
.then(response => {
if (!response.ok) {
throw new Error();
}
return response;
})
.then(blob => blob.json())
.then(shows => {
const app = document.getElementById('app');
app.innerHTML = shows.map(({ show }) => `
<div class="col-sm movie-content">
<div class="movie-image">
${show.image ? `<img src="${show.image.medium}">` : `<img class="fallbackImage"src="design/icons/No_image_available.svg">`}
</div>
<div class="movie-info">
<h1>${show.name}</h1>
</div>
</div>
`).join(' ') || "<em>No matching shows</em>"; // ***
})
.catch(err => {
// Report the error or similar
})
}

这是有效的,因为对于空数组,.join(' ')将返回"",这是伪造的,因此"" || "<em>...</em>"会导致"<em>...</em>"。但是,如果数组不为空,您将有一个非空字符串,这将是真实的。

最新更新