ReactJs - TypeError: Cannot read property 'map' of undefined

ⅰ亾dé卋堺 提交于 2020-01-06 05:56:52

问题


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

Error:

  32 | 
  33 | return (
> 34 |   <ul>
     | ^  35 |     { this.state.rates.map(i => <li>{i.data.rates}</li>)}
  36 |   </ul>
  37 | )

Code:

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;```

回答1:


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 }
      })
  }

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.




回答2:


Axios' response returns a Promise, but your promise which is consoling the response does not. So you're basically setting your state to be {rates: undefined}. That is why you're getting that error in render. I think either you can do what Gegenwind has suggested or you can resolve a promise with the response instead of just consoling it.



来源:https://stackoverflow.com/questions/59554978/reactjs-typeerror-cannot-read-property-map-of-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!