ReactJs-TypeError:无法读取未定义的属性"map" [英] ReactJs - TypeError: Cannot read property 'map' of undefined
问题描述
我正在尝试提取数据=>加密货币汇率.请在此处查看API规范: https://rapidapi.com/coingecko/api/coingecko?endpoint = apiendpoint_a6893c7b-2094-4a19-9761-0c0306fe741a ,但出现 TypeError:无法读取未定义的属性地图"
I am trying to pull data => Crypto Exchange rates. See API spec here: https://rapidapi.com/coingecko/api/coingecko?endpoint=apiendpoint_a6893c7b-2094-4a19-9761-0c0306fe741a but getting TypeError: Cannot read property 'map' of undefined
错误:
32 |
33 | return (
> 34 | <ul>
| ^ 35 | { this.state.rates.map(i => <li>{i.data.rates}</li>)}
36 | </ul>
37 | )
代码:
import React from 'react';
import './App.css';
import prettyFormat from 'pretty-format';
import axios from 'axios';
class App extends React.Component {
state = {
rates: []
}
componentDidMount() {
axios({
"method":"GET",
"url":"https://coingecko.p.rapidapi.com/exchange_rates",
"headers":{
"content-type":"application/octet-stream",
"x-rapidapi-host":"coingecko.p.rapidapi.com",
"x-rapidapi-key":"f4756b8409msh762478a357cd070p10685fjsnce9080fa5478"
}
})
.then((response)=>{
console.log(response)
})
.then(rates => this.setState({ rates}))
}
render() {
console.log(prettyFormat(this.state.data))
return (
<ul>
{ this.state.rates.map(i => <li>{i.data.rates}</li>)}
</ul>
)
}
}
export default App;```
推荐答案
据我所知,您对响应的处理不正确.您链接了两个then
语句.您可能需要在第一个then
中访问费率数据并将其设置为状态:
As far as I can tell your processing of the response is incorrect. You chained two then
statements. What you probably need is within the first then
to access the rates data and set it as state:
componentDidMount() {
axios({
"method":"GET",
"url":"https://coingecko.p.rapidapi.com/exchange_rates",
"headers":{
"content-type":"application/octet-stream",
"x-rapidapi-host":"coingecko.p.rapidapi.com",
"x-rapidapi-key":"f4756b8409msh762478a357cd070p10685fjsnce9080fa5478"
}
})
.then((response)=>{
console.log(response)
//response is an object with a data property that contains the rates
const { rates } = response.data;
this.setState({ rates }
})
}
我不确定您使用的API是什么,但是您还应该考虑注意未定义response.data.rates的情况.在上面的代码率将等于undefined
并且没有map属性.
I am not sure about the API you are using, but you should also consider taking care of a situation where response.data.rates is undefined. In the above code rates will equal to undefined
and does not have a map property.
例如,您可以检查费率是否是您期望的数组.
For example you could check if rates is an array as you expect.
这篇关于ReactJs-TypeError:无法读取未定义的属性"map"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!