如何将API信息显示到ReactDOM



目前我正在Rapid API中从雅虎金融获取股票数据。我可以将股票的"出价"记录到控制台,并将任何信息记录到控制台。然而,我似乎找不到如何在浏览器中在一个简单的网页上实际显示它的解决方案。

这是我目前拥有的

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

您需要使用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

最新更新