gpt4 book ai didi

javascript - 在 React 组件中获取数据的位置

转载 作者:行者123 更新时间:2023-11-30 11:15:39 24 4
gpt4 key购买 nike

我正在尝试感受一下前端开发的新手 reactjs。 Google Books API 很简单,所以我决定用它来构建一个 react 页面,在给定用户输入的情况下列出 10 本书。

import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';

const GOOGLE_BOOKS_API = 'https://www.googleapis.com/books/v1/volumes?q=';
const GOOGLE_BOOKS_API_LIMIT = 'maxResults=10';

class BookItem extends React.Component {
render() {
return (
<div>
<img alt="Book" src={this.props.data.volumeInfo.imageLinks.thumbnail} />
<span>{this.props.data.volumeInfo.imageLinks.thumbnail}</span>
</div>
);
}
}

class BookResults extends React.Component {
render() {
const isBookResultsEmpty = !(this.props.books && this.props.books.length > 1);
const bookItems = isBookResultsEmpty ? [] : this.props.books.map((book,index) =>
<BookItem key={index} data={book} />
);
return (
<div className='book-results'>
{isBookResultsEmpty ? (
<h1>No Results</h1>
) : (
<div> {bookItems} </div>
)}
</div>
);
}
}

class BookSearch extends React.Component {
constructor(props) {
super(props);
this.state = {
bookQuery: '',
books: []
};
this.handleInputChange = this.handleInputChange.bind(this);
this.getBooks = this.getBooks.bind(this)
}

getBooks() {
let queryString = '';
if (this.state.bookQuery && this.state.bookQuery.length > 1) {
queryString = this.state.bookQuery.replace(/\s/g, '+');
fetch(`${GOOGLE_BOOKS_API}${queryString}&${GOOGLE_BOOKS_API_LIMIT}`)
.then(results => {
return results.json();
})
.then(json => {
this.setState({
books: json.items
});
})
.catch(e => console.log('error', e));
}
}

handleInputChange(event) {
this.setState({
bookQuery: this.search.value
},
this.getBooks());
}

render() {
return (
<div className="book-search">
<form>
<input
placeholder="Search for Books"
ref={input => this.search = input}
onChange={this.handleInputChange}
/>
</form>
<BookResults books={this.state.books} />
</div>
);
}
}

ReactDOM.render(<BookSearch />, document.getElementById('root'));

输入时出现错误:

TypeError: Cannot read property 'thumbnail' of undefined

我在 BookResults 组件中添加了数据检查,但错误仍然存​​在。我认为它与渲染时状态或 Prop 值的变化有关,但我对 React 的了解还不够确定

最佳答案

有些书没有imageLinks,所以在使用之前需要确保它不是undefined

示例

class BookItem extends React.Component {
render() {
const { imageLinks } = this.props.data.volumeInfo;

if (!imageLinks) {
return null;
}

return (
<div>
<img alt="Book" src={imageLinks.thumbnail} />
<span>{imageLinks.thumbnail}</span>
</div>
);
}
}

关于javascript - 在 React 组件中获取数据的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com