reactjs - 如何向 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
解决方案
您需要使用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
推荐阅读
- xcode - 有没有办法在构建阶段检查 Circle CI 环境?
- graph - 将 Edge-Label Graph 转换为等效的 Node-Labeled
- google-cloud-interconnect - 受限.googleips.com 的合作伙伴互连,需要哪些 BGP 广告?
- python - 如何在新键下对 json 中的某些字段进行分组?
- python - django后台JSON代码错误
- javascript - 如何在 if 和 else 条件下正确使用 event.code 和 event.button?
- angular - 'string | 类型的参数 null' 不可分配给“字符串”类型的参数。“null”类型不能分配给“String”类型。[角度]
- node.js - MongoDB按对象属性值对嵌套的对象数组进行排序
- html - flexbox下拉菜单项不会弯曲
- reactjs - 您如何在个人项目中实际使用 Github 存储库?我无法将此 Typescript 项目实施到我的 React 应用程序中