我正在使用一个显示加密货币数据的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;
我能够使用 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]也没有。硬币名称(等...
当您想要迭代this.state.coinList.Data
时,您正在迭代this.state.coinList
。
试试这个:
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>
);
}
代码沙盒在这里: https://codesandbox.io/s/3rvy94myl1
和你一样的问题。无法访问数据中的对象,因为在渲染发生时该对象为空。
我所做的是我做了一个条件渲染,如果数据为空,它只会显示一个加载屏幕或类似的东西。当数据加载时,它将访问该数据中的对象。我现在可以访问里面的对象,因为我等待数据在渲染中加载。
我希望这个答案可以帮助未来的用户做出反应
return (
<div>
{this.state.coinList.length>0? <h1>{this.state.coinList[0].coinName}</h1>: "Loading"}
</div>
);
}
增加:为了控制台.log数据,您可以在条件渲染中创建新组件。在该组件中,您可以访问所需的所有数据,因为它是在加载数据后呈现的。
您可能需要解析 JSON。在保存之前这样做可能会很好。
const coins = JSON.parse(res.data)