【问题标题】:ReactJs - TypeError: Cannot read property 'map' of undefinedReactJs - TypeError:无法读取未定义的属性“地图”
【发布时间】:2020-04-20 14:59:56
【问题描述】:

我正在尝试提取数据 => 加密货币汇率。请参阅此处的 API 规范:https://rapidapi.com/coingecko/api/coingecko?endpoint=apiendpoint_a6893c7b-2094-4a19-9761-0c0306fe741a 但得到 TypeError: Cannot read property 'map' of undefined

错误:

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

代码:

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

【问题讨论】:

    标签: reactjs api axios


    【解决方案1】:

    Axios 的响应返回一个 Promise,但你安慰响应的 Promise 没有。所以你基本上将你的状态设置为{rates: undefined}。这就是为什么您在渲染中遇到该错误的原因。我认为要么你可以按照 Gegenwind 的建议去做,要么你可以通过响应来解决一个承诺,而不仅仅是安慰它。

    【讨论】:

      【解决方案2】:

      据我所知,您对响应的处理不正确。您链接了两个 then 语句。您可能需要在第一个 then 中访问费率数据并将其设置为状态:

        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,但您也应该考虑处理未定义 response.data.rates 的情况。在上面的代码中,rates 将等于undefined,并且没有 map 属性。

      例如,您可以检查 rate 是否为您所期望的数组。

      【讨论】:

        猜你喜欢
        • 2018-02-08
        • 2020-11-18
        • 2021-07-11
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多