【发布时间】:2019-11-25 21:43:40
【问题描述】:
我在 react.js 中进行了 fetch API 调用,并将其放入包含 fetch 函数的函数中定义的变量中。但是如何将这个值转移到状态中的变量之一呢?我可以到 console.log 变量的地步,但我仍然无法弄清楚如何更新状态变量之一,以便我可以将检索到的数据显示到页面上。
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”。
感谢您的帮助!
【问题讨论】:
-
如果我在 fetch api 调用区域中使用 'this.setState' 方法,'this' 部分无法引用正确的位置,也许我可以将其更改为以某种方式引用状态正确吗?
-
您应该能够在第二个
then方法中使用this.setState。在.then中使用箭头函数,使其指向正确的上下文 -
在获取之前使用 _this=this 并使用 _this.setState @SimonSuh
标签: javascript reactjs api state prop