0

我正在尝试制作一个小应用程序来跟踪我读过的书籍,并且我正在使用 Google Books API。我的电话是正确的,但是在访问 JSON 数据时,我似乎无法选择正确的元素?(即标题、作者等)我会认为 kind、totalitems 和 items 元素是前 3 个元素,其中 items 是一个数组。当使用“books.items”调用时,它显示为空,当填充数组调用时books.items[0]显示类型错误:

“无法读取未定义的属性‘0’

我尝试过一些随机组合,但似乎没有任何效果

我正在“改编”来自 pusher.com 的本指南(这只是一个小项目),链接是:https ://pusher.com/tutorials/consume-restful-api-react

我的 app.js

import React, {Component} from 'react';
import Books from './components/books';

const apikey = 'my key here'
const isbn = '9780395647417'
const url = 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn + '?projection=lite&key=' + apikey;
class App extends Component {
    render() {
        return (
            <Books books={this.state.books} />
        )
    }

    state = {
        books: []
    };

    componentDidMount() {
        fetch(url)
            .then(res => res.json())
            .then((data) => {
                this.setState({ books: data })
            })
            .catch(console.log)
    }
}

export default App;

我的书组件

import React from 'react'

const Books = ({books}) => {
    return (
        <div>
         {books.items[]}
        </div>
    )
};

export default Books

返回的对象

{
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "jlytxgEACAAJ",
"etag": "Kq99jRrSq+c",
"selfLink": "https://www.googleapis.com/books/v1/volumes/jlytxgEACAAJ",
"volumeInfo": {
"title": "The Lord of the Rings",
"authors": [
"John Ronald Reuel Tolkien"
],
"publishedDate": "1994",
"description": "The Fellowship was scattered. Some were bracing hopelessly for war against the ancient evil of Sauron.",
"industryIdentifiers": [],
"readingModes": {},
"printType": "BOOK",
"categories": [],
"averageRating": 5,
"ratingsCount": 1,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"panelizationSummary": {},
"language": "en",
"previewLink": "http://books.google.co.uk/books?id=jlytxgEACAAJ&dq=isbn:9780395647417&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.uk/books?id=jlytxgEACAAJ&dq=isbn:9780395647417&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/The_Lord_of_the_Rings.html?hl=&id=jlytxgEACAAJ"
},
"saleInfo": {},
"accessInfo": {},
"searchInfo": {}
}
]
}
4

2 回答 2

1

两件事情:

一,在组件的第一部分中看到 render 方法非常奇怪。始终将渲染作为组件中的最后一个方法(如果可能,使用钩子和功能组件并使用无效渲染方法)

第二,

什么是 sintax books.items[]?如果你想渲染“books”对象的每一项,你应该在 Books 组件中这样做:

<div>
{books.items.map(item => <div key={item.id}>{item.title}</div>)
</div>

每个项目都有一个 div 显示标题(你可以显示你需要的属性...)

于 2020-05-07T03:22:25.240 回答
0
books.items.map((item,index) =>(
 <div key={index}>
   <h1>{item.title}</h1>
   
 </div>
))
于 2021-07-18T05:11:22.417 回答