【问题标题】:Getting [Object] from Coindesk API instead of a JavaScript object从 Coindesk API 获取 [Object] 而不是 JavaScript 对象
【发布时间】:2020-07-26 11:01:40
【问题描述】:

我正在使用 Nextjs,并从 Coindesk 的 API 获取比特币的当前价格:

https://api.coindesk.com/v1/bpi/currentprice.json

我在Home 组件中获取了数据,在这个组件中,我得到了正确的 json 数据。我将此数据作为道具发送到Prices 组件,但它没有在此组件中正确记录。 axios 有问题吗?


而不是这个:bpi: { USD: {...}, GBP: {...}, EUR: {...} }

我收到了这个:bpi: { USD: [Object], GBP: [Object], EUR: [Object] }


Home.js

import Layout from "../components/Layout"
import Prices from "../components/Prices"
import axios from "axios"

const Home = (props) => {
  return (
    <Layout>
      <div>
        <h1>Welcome to Bitzprice</h1>
        <Prices bpiData={props.bpiData} />
      </div>
    </Layout>
  )
}

Home.getInitialProps = async function () {
  const res = await axios.get(
    "https://api.coindesk.com/v1/bpi/currentprice.json"
  ) 
  const data = res.data
  console.log("DATA=>", data)
  return {
    bpiData: data,
  }
}

export default Home

Prices.js

class Prices extends React.Component {
  state = {
    currency: "USD",
  }

  render() {
    console.log("PROPS=>", this.props)
    return (
      <div>
        ....
      </div>
    )
  }
}

export default Prices



DATA=> {
    time: {
      updated: 'Jul 26, 2020 10:29:00 UTC',
      updatedISO: '2020-07-26T10:29:00+00:00',
      updateduk: 'Jul 26, 2020 at 11:29 BST'
    },
    disclaimer: 'This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org',
    chartName: 'Bitcoin',
    bpi: {
      USD: {
        code: 'USD',
        symbol: '&#36;',
        rate: '9,983.2870',
        description: 'United States Dollar',
        rate_float: 9983.287
      },
      GBP: {
        code: 'GBP',
        symbol: '&pound;',
        rate: '7,804.6243',
        description: 'British Pound Sterling',
        rate_float: 7804.6243
      },
      EUR: {
        code: 'EUR',
        symbol: '&euro;',
        rate: '8,564.9015',
        description: 'Euro',
        rate_float: 8564.9015
      }
    }
  }

PROPS=> {
  bpiData: {
    time: {
      updated: 'Jul 26, 2020 10:29:00 UTC',
      updatedISO: '2020-07-26T10:29:00+00:00',
      updateduk: 'Jul 26, 2020 at 11:29 BST'
    },
    disclaimer: 'This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org',
    chartName: 'Bitcoin',
    bpi: { USD: [Object], GBP: [Object], EUR: [Object] }
  }
}

【问题讨论】:

    标签: javascript json reactjs api fetch


    【解决方案1】:

    数据可能是正确的,[对象]只是一个快捷方式,以避免显示复杂的嵌套对象。如果你做console.log("DATA=&gt;", JSON.stringify(data)),你会得到完整的数据。

    【讨论】:

    • this.props.bpiPrices.js 中给我未定义。
    • 正常,应该是this.props.bpiData.bpi
    猜你喜欢
    • 2022-01-02
    • 2021-04-15
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2019-07-24
    • 2021-04-05
    • 2021-09-13
    相关资源
    最近更新 更多