gpt4 book ai didi

javascript - 进行 fetch 调用时出错

转载 作者:行者123 更新时间:2023-12-03 03:41:29 26 4
gpt4 key购买 nike

如何循环遍历数组中的多个属性以及如何使用map函数将数组中的多个属性显示到网页

import React, { Component } from 'react';

import './App.css';

class App extends Component {
constructor(){
super();
this.state={
booksLists:'',
description: ''
}
}
componentWillMount() {
fetch('https://reactnd-books-api.udacity.com/books', { headers: {
'Authorization': 'whatever-you-want' }})
.then(res => res.json())
.then(res => {
this.setState({booksLists: res})
})
}

render() {
let booksLists = this.state.booksLists;
console.log(booksLists)

return (
<div className="App">
<h2>My Reads</h2>
<p></p>
</div>
);
}
}

导出默认应用程序;

最佳答案

这是一个 CodePen Demo ,或者您可以运行下面的代码片段:

class App extends React.Component {
constructor() {
super();
this.state = {
booksLists: []
};
}
componentWillMount() {
fetch("https://reactnd-books-api.udacity.com/books", {
headers: {
Authorization: "whatever-you-want"
}
}).then(res => res.json()).then(res => {
this.setState({booksLists: res.books});
});
}

render() {
const {booksLists} = this.state;
const books = booksLists
? booksLists.map(book => <div className='panel panel-default col-xs-12'>
<div className='panel-heading'>
<h3>{book.title || 'not available'}</h3>
<h5>{book.subtitle || 'not available'}</h5>
</div>
<div className='panel-body'>
<div className='row'>
<div className='col-xs-4'>
<img className='img-responsive' src={book.imageLinks.smallThumbnail}/>
</div>
<div className='col-xs-8'>
<p>
<strong>Authors: </strong>
{book.authors
? book.authors.join(', ')
: 'not available'}</p>
<p>
<strong>Publisher: </strong>
{book.publisher || 'not available'}</p>
<p>
<strong>Date of publication: </strong>
{book.publishedDate || 'not available'}</p>
</div>
</div>
<div className='row'>
<div className='col-xs-12'>
<p>{book.description || 'not available'}</p>
</div>
</div>
</div>
</div>)
: null;

return (
<div className="App">
<h2>My Reads</h2>
{books}
</div>
);
}
}

ReactDOM.render(
<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />


<div id='root'></div>

关于javascript - 进行 fetch 调用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45599832/

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