首页 > 解决方案 > 如何向 ReactDOM 显示 API 信息?

问题描述

目前我正在从 Rapid API 中的 yahoo Finance 获取股票数据。我能够将股票的“出价”记录到控制台,并将任何信息记录到控制台。但是,我似乎无法找到如何在简单网页上的浏览器中实际显示它的解决方案。

这是我到目前为止所拥有的

import React from "react";



const Test = () => {



fetch("https://yh-finance.p.rapidapi.com/market/v2/get-quotes?region=US&symbols=VTI%2C%20AAPL%2CTSLA%2CFB", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "yh-finance.p.rapidapi.com",
        "x-rapidapi-key": "api-key"
    }
})
.then(res => res.json())

.then(res => {
    console.log(res.quoteResponse.result[3].bid)
})



    return (
        <>
        <h1>{}</h1>
        </>
    )
}



export default Test

标签: reactjsreact-nativereact-dom

解决方案


您需要使用useState来管理存储 api 响应的状态,并使用useEffect来更好地管理 api 调用。阅读上下文 api 的文档。

同时,以下解决方案应该有效

import React, {useState, useEffect} from "react";



const Test = () => {
const [apiResponse, setApiResponse] = useState('')

useEffect(() => {
  fetch("https://yh-finance.p.rapidapi.com/market/v2/get-quotes?region=US&symbols=VTI%2C%20AAPL%2CTSLA%2CFB", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "yh-finance.p.rapidapi.com",
        "x-rapidapi-key": "api-key"
    }
})
.then(res => setApiResponse(res.json()))

.then(res => {
    console.log(res.quoteResponse.result[3].bid)
})
},[])




    return (
        <>
        <h1>{apiResponse}</h1>
        </>
    )
}



export default Test

推荐阅读