javascript - 如何使用我使用 fetch API 调用检索到的数据更新 Reactjs 状态?
问题描述
我在 react.js 中进行了 fetch API 调用,并将其放在包含 fetch 函数的函数中定义的变量中。但是如何将这个值转移到状态中的变量之一呢?我可以到控制台记录变量的地步,但我仍然无法弄清楚如何更新状态变量之一,以便我可以将检索到的数据显示到页面上。
import React from 'react';
class Stock extends React.Component {
constructor(props) {
super(props);
this.state = {
stockInfo: '100'
}
}
componentDidMount() {
this.fetchStock();
}
fetchStock() {
const API_KEY = 'api key goes here';
let TimeInterval = '60min';
let StockSymbol = 'AMZN';
let API_Call = `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${StockSymbol}&interval=${TimeInterval}&outputsize=compact&apikey=${API_KEY}`;
let stockHistoryDatabase = {};
let stockHistoryDatabaseString;
fetch(API_Call)
.then(
function(response) {
return response.json();
}
)
.then(
function(data) {
console.log(data);
for (var key in data['Time Series (60min)']) {
// push the key value pair of the time stamp key and the opening value key paired together into an object with a key value pair data set storage.
var epochKeyTime = new Date(key);
epochKeyTime = epochKeyTime.getTime();
stockHistoryDatabase[epochKeyTime] = data['Time Series (60min)'][key]['1. open'];
}
console.log(stockHistoryDatabase);
stockHistoryDatabaseString = JSON.stringify(stockHistoryDatabase);
console.log(stockHistoryDatabaseString);
}
);
}
handleChange = () => {
this.setState({
stockInfo: 'hello'
});
}
render() {
return(
<div>
<h1>Stocks</h1>
<p>{this.state.stockInfo}</p>
<button onClick={this.handleChange}>Change</button>
</div>
);
}
}
export default Stock;
这是我的全部代码。我知道如何使用从同一页面上的按钮单击调用的单独函数来更改状态,但是我无法获取存储在变量“stockHistoryDatabaseString”中的数据来替换状态“stockInfo”。
感谢您的帮助!
解决方案
由于您fetchStock
在组件安装后调用。您可以按如下方式使用箭头功能。
.then((data) => {
// use data here
this.setState({ ... }) // set you state
})
或者如果您不习惯使用箭头函数,那么我相信您可以创建一个函数来处理承诺,例如handleData
.then(this.handleData)
在班上
// pseudo code
class YourClass extends React.Component {
componentDidMount() {
this.fetchStock()
}
handleData = (data) => {
// process your data and set state
}
fetchStock() {
// your API call
fetch(API_CALL).then(this.handleData);
}
render() {}
}
如果您正在调用fetchStock
用户操作,例如按钮单击,那么您可以fetchStock
通过将其绑定到您创建的 React 类来提供适当的上下文,如下所示:
constructor() {
this.fetchStock = this.fetchStock.bind(this);
}
或者有另一种方法来实现相同的(也许更清洁的方式):
fetchStock = () => {
}
推荐阅读
- rsa - Powerbuilder 9.0.3 和 Powerbuilder 12.6 的 Chilkat RSASSA-PSS 签名问题
- javascript - 无法在 react native 中访问资产子文件夹中的资产文件
- java - @StepScope Causing 问题阅读器必须先打开才能阅读
- c# - 如何在 asp.net core 中创建图表
- javascript - 打印窗口出现后关闭弹出窗口
- python-requests - 对 api 的多个请求
- java - 结构中的 OPCUA milo 自定义数据类型结构可能吗?
- javascript - Javascript:删除两个括号之外的字母
- istio - 流量拆分是否需要 Istio 入口网关?
- javascript - Material UI TextField input type="date" 没有得到 event.target.value