使用 React/Axios 访问对象内的 JSON 对象

Nic*_*len 0 api json object reactjs axios

我正在使用一个 API,该 API 显示名为 CryptoCompare 的加密货币数据。我是一个 React 菜鸟,但我已经设法使用 Axios 来执行 AJAX 请求。但是,我无法访问我想要的 JSON 元素。

这是 JSON 的样子:https : //min-api.cryptocompare.com/data/all/coinlist

这是我的要求:

import React, { Component } from 'react';
import './App.css';
import axios from "axios";
var NumberFormat = require('react-number-format');

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      coinList: []
    };
  }



  componentDidMount() {
    axios.get(`https://min-api.cryptocompare.com/data/all/coinlist`)
    .then(res => {
      const coins = res.data;
      //console.log(coins);
      this.setState({ coinList: coins});
    });
  }



// Object.keys is used to map through the data. Can't map through the data without this because the data is not an array. Map can only be used on arrays.
  render() {
    console.log(this.state.coinList.Data);
    return (
      <div className="App">
        {Object.keys(this.state.coinList).map((key) => (
          <div className="container">
            <span className="left">{key}</span>
            <span className="right"><NumberFormat value={this.state.coinList[key].CoinName} displayType={'text'} decimalPrecision={2} thousandSeparator={true} prefix={'$'} /></span>
          </div>
        ))}
      </div>
    );
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

我可以使用 console.log(this.state.coinList.Data); 输出一些 JSON。它输出 JSON 对象,但我无法控制台.log 对象本身的属性。

例如,我将如何输出第一个元素 42 的 CoinName 属性?

console.log(this.state.coinList.Data.CoinName) 不起作用

console.log(this.state.coinList.Data[0].CoinName) 等也没有……

kLa*_*abz 5

this.state.coinList当您想迭代时,您正在迭代this.state.coinList.Data

尝试这个:

  render() {
    const data = this.state.coinList.Data;
    if (data == null) return null;
    return (
      <div className="App">
        {Object.keys(data).map((key) => (
          <div className="container">
            <span className="left">{key}</span>
            <span className="right"><NumberFormat value={data[key].CoinName} displayType={'text'} decimalPrecision={2} thousandSeparator={true} prefix={'$'} /></span>
          </div>
        ))}
      </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

CodeSandbox 在这里:https ://codesandbox.io/s/3rvy94myl1