javascript - React 循环遍历对象数组
问题描述
我从 coinlayer 获取了一个 api,它返回的数据是一个对象。我尝试使用 state 创建一个空数组,然后 setState 在那里设置数据,但是当我尝试使用 map 循环遍历它时,生成的错误显示“map is not a function”
来自 api 的数据的屏幕截图
这是代码
class App extends Component{
state={names:[] }
componentDidMount(){
fetch('http://api.coinlayer.com/live?access_key=c8c0ef65a659c37726364c68e6fdb887&expand=1')
.then((response)=>response.json())
.then((data)=>{
console.log(data.rates);
this.setState({names:data.rates})
})
}
render(){
return(
<div className="Body">
<div className="Navbar"><h1 style={{textAlign:'center'}}>Crypto Dashboard</h1></div>
<DashBoard names={this.state.names} />
</div>
)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
导出默认应用程序;
解决方案
您正在尝试使用对象,而不是数组。
您可以使用Object.keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
例如
fetch('http://api.coinlayer.com/live?access_key=c8c0ef65a659c37726364c68e6fdb887&expand=1')
.then((response)=>response.json())
.then((data)=>{
let names = [
Object.keys(data).forEach(key => {
names.push(data[key]) // Push the values to the array
names.push(key]) // Or push the key to the array (whatever you need)
})
this.setState({ names })
})
还有许多其他方法可以做到这一点。
推荐阅读
- sql-server - 长期运行的分阶段后端处理的 SQL 完整性问题
- powershell - 对于包含哈希 (#) 的文件夹名称,Add-PnPFolder 失败
- javascript - 渲染过程中 IPCRenderer 的电子错误
- python - 如何创建一个数据框,其中包含一个键下的二维列表?
- python - 如何从大文件名数组中测试文件是否存在,如果文件名不以一致的方式存在,如何从数组中删除文件名?
- python - 无法将数据框转换为 stata 格式
- javascript - javascript 验证 lang, lat 为 dmc 格式
- qt - QApplication 从分段错误中恢复
- php - 如何获取artifactsrequests 表的ID,而不是我加入的表的ID
- python - 如何找到一维数组/向量的自相关矩阵