如何使JSON响应数据全局化:)



目前正在为我的投资组合做一个股票项目,我正在使用finnhub作为API。我可以将所有内容记录到我的控制台上。然而,我不能将其呈现为";数据";不是全局声明的,必须在某个函数内部。

我尝试在全球范围内渲染,但没有成功。。。

因此,我的问题是如何使"数据"全局化,以便在";StockHeader的";回来

这是我目前所拥有的。。。

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

const StockHeader  = (data) => {
const [stocks, setStocks] = useState({});
const getStocks = () => {
//setting stocks
setStocks(stocks)
}
//calling it once
useEffect(()=> {
getStocks();
}, [])

//using finhubs ready made code from documentation
const finnhub = require('finnhub');
const api_key = finnhub.ApiClient.instance.authentications['api_key'];
api_key.apiKey = "my apikey" 
const finnhubClient = new finnhub.DefaultApi()
finnhubClient.quote("AAPL", (error, data, response) => {
//I can log the data but I cant show it in my component
console.log(data.c)
});
return (
<>
{/* This says that data is not defined */}
<h1>{data.c}</h1>
</>
)

}

export default StockHeader 

您只需要一点代码重组,这样API请求只发生一次,这样您就可以使用setStocks来存储它:

const StockHeader  = (data) => {
const [stocks, setStocks] = useState({});
useEffect(()=> {
//this could be separated into a `getStocks` function if you want
const finnhub = require('finnhub');
const api_key = finnhub.ApiClient.instance.authentications['api_key'];
api_key.apiKey = "my apikey" 
const finnhubClient = new finnhub.DefaultApi()
finnhubClient.quote("AAPL", (error, data, response) => {
console.log(data.c);
setStocks(data.c);
});
}, []);
return (
<>
{/* You probably don't want to render `stocks` itself, but this shows you how to get access to the variable */}
<h1>{stocks}</h1>
</>
)
}

最新更新