亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲得反應返回元素的長度?

如何獲得反應返回元素的長度?

慕哥9229398 2021-09-30 10:25:21
我想獲得 {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>

編輯以檢查未定義,謝謝丹妮。


查看完整回答
反對 回復 2021-09-30
?
慕沐林林

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>


查看完整回答
反對 回復 2021-09-30
  • 2 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號