首页 > 解决方案 > TypeError:this.state.fromCoin.map 不是函数

问题描述

我正在尝试做一个基本的交换应用程序。我找不到解决标题中写的错误的解决方案。这是我的反应代码:首先定义“状态”;

import React, { Component } from "react";
import axios from "axios";

export default class Exchange extends Component {
  constructor(props) {
    super(props);

    this.state = {
      rate: "",
      amount: "",
      result: "",
      fromCoin: "",
      toCoin: ""
    };
  }

然后从 API 获取数据:

componentDidMount() {
    axios.get("https://api.exchangeratesapi.io/latest?base=USD")
    .then((res) => { this.setState({

        rate: res.data.rates.TRY,
        fromCoin: Object.keys(res.data.rates),
        toCoin: Object.keys(res.data.rates),

      });
    });
  }

然后渲染:

render() {  
    return (
      <form>
        <section>
          {this.state.fromCoin.map((coin, index) => (
            <option key={index} value={coin}>
              {coin}
            </option>
          ))}
        </section>

        <input onChange={this.AmountHandler} type="number" />

        <button onClick={this.ExchangeHandler}>Convert</button>
       
        <section>
          {this.state.toCoin.map((coin, index) => (
            <option key={index} value={coin}>
              {coin}
            </option>
          ))}
        </section>
      </form>
    );
  }

当我打印this.state.fromCoin时,我得到一个数组。所以我认为地图功能应该在这里工作。我找不到任何解决方案。

标签: javascriptreactjs

解决方案


推荐阅读