【问题标题】:React native API data problem: TypeError:undefined is not a functionReact Native API 数据问题:TypeError:undefined is not a function
【发布时间】:2020-02-17 20:18:05
【问题描述】:

我在访问返回 JSON 的 API 时遇到了一些问题。我想在屏幕上列出来自 API 的信息,但我收到了那个错误:TypeError:undefined is not a function(near '... this.state.dataSource.map...')。 这就是 API 返回的内容:

{"rates":
{"CAD":1.3229349331,"HKD":7.7674203969,"ISK":127.0881402861,"PHP":50.564836179,"DKK":6.8944162437,
"HUF":308.8509460083,"CZK":22.882325796,"GBP":0.7682325796,"RON":4.4086755884,"SEK":9.7206275958,
"IDR":13652.496538994,"INR":71.3816335948,"BRL":4.3137055838,"RUB":63.4567604984,"HRK":6.8726349792,
"JPY":109.875403784,"THB":31.1748961698,"CHF":0.9820950623,"EUR":0.9229349331,"MYR":4.144993078,
"BGN":1.8050761421,"TRY":6.0491001384,"CNY":6.9815413013,"NOK":9.2637748039,"NZD":1.5564374712,
"ZAR":14.9603137979,"USD":1.0,"MXN":18.5734194739,"SGD":1.3887401938,"AUD":1.4886017536,
"ILS":3.4269497,"KRW":1183.848638671,"PLN":3.9335486848},
"base":"USD",
"date":"2020-02-17"}

代码:

import React, { Component } from 'react';
import { StyleSheet, Text, View, ActivityIndicator } from 'react-native';

export default class ConvertScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: []
    }
  }

  //API
  componentDidMount() {
    return fetch("https://api.exchangeratesapi.io/latest?base=USD")
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource:responseJson.rates
        })
      })
      .catch((error) => {
        return error
      })
  }
  render() {
    if (!this.state.isLoading) {
      return (
        <View style={style.container}>
          <View>
              {this.state.dataSource.map((item, id) => (
              <Text> {item} </Text>
            ))}
          </View>
        </View >
      );
    }

    else {

      return (
        <View style={style.container}>
          <View style={style.viewInit}>
            <ActivityIndicator />
          </View>
        </View>
      );
    }
  }
}

如何迭代 API 中的“费率”数据?

【问题讨论】:

  • 查看您的 API 响应,this.state.dataSource 将是一个对象,而不是一个数组 - 因此它的 .map 属性将是 undefined

标签: javascript json react-native


【解决方案1】:

您收到此错误是因为 .map 函数仅在数组上可用。

它是 {},但您期望 [],因此您可能需要使用 Object.entries(obj) 返回给定对象自己的可枚举字符串键属性 [key, value] 对的数组:

Object.entries(stats).map(([key, value]) => console.log(key, value))

使用 for..in 循环也可以解决您的问题,它会遍历由字符串键入的对象的所有可枚举属性

for (const rate in rates) {
  console.log(`${rate}: ${rates[rate]}`);
}

【讨论】:

  • 谢谢,Object.entries(stats).map(([key, value]) =&gt; console.log(key, value)) 为我工作:D
猜你喜欢
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
  • 2020-04-28
相关资源
最近更新 更多