首页 > 解决方案 > 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>

导出默认应用程序;

标签: javascriptreactjsloops

解决方案


您正在尝试使用对象,而不是数组。

您可以使用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 })
    })

还有许多其他方法可以做到这一点。


推荐阅读