[英]TypeError: this.state.rates.map is not a function - Reactjs
I am getting this error after trying to map over API response.尝试映射 API 响应后出现此错误。 Appreciate your help.
感谢你的帮助。 I am able to see response in console but
我能够在控制台中看到响应,但是
Thank you.谢谢你。
Code below:代码如下:
import React from 'react'; import './App.css'; import prettyFormat from 'pretty-format'; import axios from 'axios'; class App extends React.Component { state = { rates: [] } onSubmitExchange = this.onSubmitExchange.bind(this); onSubmitExchange() { 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 }) }) } render() { let xrpName = (this.state.rates.xrp && this.state.rates.xrp) ? this.state.rates.xrp.name : undefined console.log(xrpName) console.log(this.state.rates) const items = this.state.rates.map((item) => {return <li>{ item.name }</li> }); return ( <div> <ul> { items } </ul> <button onClick={this.onSubmitExchange}>FIRE</button> </div> ) } } export default App;
The API returns an object. API 返回一个对象。 You can't map over it like an array.
你不能像数组一样映射它。 First change
第一次改变
state = {
rates: []
}
to到
state = {
rates: {}
}
Then use Object.keys(rates)
to map over it.然后使用
Object.keys(rates)
进行映射。
Sorted with this.以此排序。 Needed to use
Object.keys()
and then map over it as Ola mentioned.需要使用
Object.keys()
然后像 Ola 提到的那样映射它。
const cryptoTable = Object.entries(cryptos).map((crypto, index) => {
return (<tr>
<td key={index}>{crypto[1].name}</td>
<td>{crypto[1].unit}</td>
<td>{crypto[1].value}</td>
<td className="tag">{crypto[1].type}</td>
</tr>)
})
return (
<div>
<div>
{ cryptoTable }
</div>
<button onClick={this.onSubmitExchange}>FIRE</button>
<button onClick={this.onFilterHandler}>Filter</button>
</div>
)
}
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.