ReactJs-TypeError:无法读取属性';地图';未定义的
我正在尝试提取数据=>加密汇率。请参见此处的API规范:但是获取类型错误:无法读取未定义的属性“map” 错误:ReactJs-TypeError:无法读取属性';地图';未定义的,reactjs,api,axios,Reactjs,Api,Axios,我正在尝试提取数据=>加密汇率。请参见此处的API规范:但是获取类型错误:无法读取未定义的属性“map” 错误: 32 | 33 | return ( > 34 | <ul> | ^ 35 | { this.state.rates.map(i => <li>{i.data.rates}</li>)} 36 | </ul> 37 | ) 32| 33 |返回( >34 | |^35{this
32 |
33 | return (
> 34 | <ul>
| ^ 35 | { this.state.rates.map(i => <li>{i.data.rates}</li>)}
36 | </ul>
37 | )
32|
33 |返回(
>34 |
|^35{this.state.rates.map(i=>- {i.data.rates}
)}
36 |
37 | )
代码:
从“React”导入React;
导入“/App.css”;
从“prettyFormat”导入prettyFormat;
从“axios”导入axios;
类应用程序扩展了React.Component{
状态={
费率:[]
}
componentDidMount(){
axios({
“方法”:“获取”,
“url”:”https://coingecko.p.rapidapi.com/exchange_rates",
“标题”:{
“内容类型”:“应用程序/八位字节流”,
“x-rapidapi-host”:“coingecko.p.rapidapi.com”,
“x-rapidapi-key”:“f4756b8409msh762478a357cd070p10685fjsnce9080fa5478”
}
})
。然后((响应)=>{
console.log(响应)
})
.then(rates=>this.setState({rates}))
}
render(){
log(prettyFormat(this.state.data))
返回(
{this.state.rates.map(i=>- {i.data.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)
//response is an object with a data property that contains the rates
const { rates } = response.data;
this.setState({ rates }
})
}
我不确定你正在使用的API,但是你也应该考虑到Acth.DATA率没有定义的情况。在上述代码中,速率将等于未定义
,并且没有映射属性
例如,您可以检查rates是否如您所期望的那样是一个数组。Axios的响应返回一个承诺,但您安慰响应的承诺没有返回。因此,您基本上将状态设置为{rates:undefined}
。这就是为什么在渲染中会出现错误。我认为要么你们可以按照Gegenwind的建议去做,要么你们可以通过回应来解决承诺,而不仅仅是安慰它
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 }
})
}