我想通过bootstrap在react应用程序中使用restful api。但是我不能正确地映射。我认为问题出在括号上。但我想不明白。(忽略我的div部分,如果我可以映射,我将更新该部分。)
我的restful api: https://api.coindesk.com/v1/bpi/currentprice.json
Restful api Json格式:
{
"time":{
"updated":"Jun 2, 2022 08:38:00 UTC",
"updatedISO":"2022-06-02T08:38:00+00:00",
"updateduk":"Jun 2, 2022 at 09:38 BST"
},
"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"chartName":"Bitcoin",
"bpi":{
"USD":{
"code":"USD",
"symbol":"$",
"rate":"29,941.3155",
"description":"United States Dollar",
"rate_float":29941.3155
},
"GBP":{
"code":"GBP",
"symbol":"£",
"rate":"23,980.6882",
"description":"British Pound Sterling",
"rate_float":23980.6882
},
"EUR":{
"code":"EUR",
"symbol":"€",
"rate":"28,094.2357",
"description":"Euro",
"rate_float":28094.2357
}
}
}
我App.js
import React, {Component} from 'react';
import Lists from './example/lists';
class App extends Component {
render() {
return (
<Lists lists={this.state.lists} />
)
}
state = {
lists: {}
};
componentDidMount() {
fetch('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(res => res.json())
.then((data) => {
this.setState({ lists: data })
})
.catch(console.log)
}
}
export default App;
我list.js:
import React from 'react'
const Lists = ({lists}) => {
return (
<div>
<center><h1>Exchange</h1></center>
{lists.map((list) => (
<div class="card">
<div class="card-body">
<h5 class="card-title">{list.time}</h5>
<h5 class="card-title">{list.bpi}</h5>
</div>
</div>
))}
</div>
)
};
export default Lists
json不是一个数组,因此不需要通过它来map
。从List组件中删除映射。
import React from 'react'
const Lists = ({lists}) => {
return (
<div>
<center><h1>Exchange</h1></center>
<div class="card">
<div class="card-body">
<h5 class="card-title">{lists.time}</h5>
<h5 class="card-title">{lists.bpi}</h5>
</div>
</div>
</div>
)
};
export default Lists
我不确定你的json是完整的,但是,因为你的json返回一个对象,你不能使用映射或任何循环。您只需要显示数据而不循环