我想获得 {book.volumeInfo.description} 元素的长度来检查描述是否为空(如果 {book.volumeInfo.description} >0 {...} else { "Book without description"}我不知道如何以适当的方式获得此 {book.volumeInfo.description} 元素的长度。你有什么理由来解决这个问题吗?应用程序.jsimport React, { useState } from "react";import ReactDOM from "react-dom";import axios from "axios";import 'bootstrap/dist/css/bootstrap.min.css';const App = () => {const [searchTerm, setSearchTerm] = useState("");const [books, setBooks] = useState({ items: [] });const onInputChange = e => { setSearchTerm(e.target.value);};let API_URL = 'https://www.googleapis.com/books/v1/volumes';const fetchBooks = async () => { const result = await axios.get(`${API_URL}?q=${searchTerm}`); setBooks(result.data);};const onSubmitHandler = e => { e.preventDefault(); fetchBooks();};return ( <section> <form onSubmit={onSubmitHandler}> <label> <span>Search for books</span> <input type="search" placeholder="microservice, restful design, etc.," value={searchTerm} onChange={onInputChange} /> <button type="submit">Search</button> </label> </form> <ul> {books.items.map((book, index) => { return ( <div> <div class="row"> <div class="col-12"> <center> <h5>{book.volumeInfo.title}</h5> </center> <center> <h5>{book.volumeInfo.categories} </h5></center> <center> <h5>{book.volumeInfo.authors} </h5></center> <center> <h5>{book.volumeInfo.language} </h5></center> <center> <h5> {book.volumeInfo.publishedDate}</h5></center> <center> <h5>
2 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
您可以使用三元运算符有条件地显示您需要的文本。
<h5>
{book.volumeInfo.description && book.volumeInfo.description.length > 0 ? book.volumeInfo.description : "Book without description"}
</h5>
编辑以检查未定义,谢谢丹妮。
慕沐林林
TA贡献2016条经验 获得超9个赞
在使用之前,请确保您拥有此对象(“book.volumeInfo.description”)并且自然也是对象,
<h5>{typeof(book.volumeInfo.description) == "object" && book.volumeInfo.description &&
book.volumeInfo.description.length > 0 ? book.volumeInfo.description : 'book without description'}</h5>
添加回答
举报
0/150
提交
取消