首页 > 解决方案 > coinList.maps 不是函数错误如何将对象转换为数组?

问题描述

var NumberFormat = require("react-number-format");

export default class Coinlist extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      coinList: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://min-api.cryptocompare.com/data/all/coinlist&api_key="
    )
      .then(res => res.json)
      .then(json => {
        this.setState({
          isLoaded: true,
          coinList: json
        });
      });
  }

  render() {
    var { isLoaded, coinList } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="Coinlist">
          <ul>
            {coinList.maps(coins => (
              <li key={coins.Name}>{coins.Id}</li>
            ))}
            ;
          </ul>
        </div>
      );
    }
  }
}

我对“TypeError:coinList.maps 不是函数”有疑问,我需要将对象 coinList 转换为数组,但不知道如何操作。如果有人可以帮助我解决这个问题,我将不胜感激。我对这一切都很陌生

标签: javascriptarraysreactjs

解决方案


您可以尝试将coinList.Data.BTC.NamecoinList.Data.BTC.Id映射到 UI。

如果您想要所有硬币,请尝试以下代码。

const coinDetails = Object.values(coinList.Data);
coinDetails.forEach(cd => console.log(cd.Name + ' ' + cd.Id));

上面的代码将在控制台中为您提供值。我希望这将帮助您获取值并在 UI 中使用它。


推荐阅读