[英]How do I update Reactjs State with data I retrieved using a fetch API call?
I made a fetch API call in react.js and put it inside a variable defined within the function containing the fetch function.我在 react.js 中进行了 fetch API 调用,并将其放在包含 fetch 函数的函数中定义的变量中。 But how do I transfer this value to one of the variables in the state?
但是如何将这个值转移到状态中的变量之一呢? I can get to the point where I console.log the variable, but still I'm not able to figure out how to update one of the state variables so that I can then display the retrieved data onto the page.
我可以到控制台记录变量的地步,但我仍然无法弄清楚如何更新状态变量之一,以便我可以将检索到的数据显示到页面上。
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;
this is my code in entirety.这是我的全部代码。 I know how to change the state using a separate function that is called from a button click on the same page, but I'm unable to get the data stored in the variable 'stockHistoryDatabaseString' to replace the state 'stockInfo'.
我知道如何使用从同一页面上的按钮单击调用的单独函数来更改状态,但是我无法获取存储在变量“stockHistoryDatabaseString”中的数据来替换状态“stockInfo”。
Thank you for the help!感谢您的帮助!
Since you are calling fetchStock
after component is mounting.由于您在安装组件后调用
fetchStock
。 You can use arrow function as follows.您可以按如下方式使用箭头功能。
.then((data) => {
// use data here
this.setState({ ... }) // set you state
})
or if you are not comfortable using arrow function, then I believe you can create a function to handle the promise eg handleData
或者如果您不习惯使用箭头函数,那么我相信您可以创建一个函数来处理承诺,例如
handleData
.then(this.handleData)
in class在班上
// 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() {}
}
If you are invoking fetchStock
on user operation, such as button click, then you can provide appropriate context to fetchStock
by binding it to React class you've created as follows:如果您在用户操作上调用
fetchStock
,例如按钮单击,那么您可以通过将其绑定到您创建的 React 类来为fetchStock
提供适当的上下文,如下所示:
constructor() {
this.fetchStock = this.fetchStock.bind(this);
}
or there is another way to achieve the same (perhaps cleaner way):或者有另一种方法来实现相同的(也许更清洁的方式):
fetchStock = () => {
}
First inside constructor add首先在构造函数中添加
this.fetchStock = this.fetchStock.bind(this);
I had a similar problem.我有一个类似的问题。 My solution to this problem was to store
this
context of react class into one variable and then use it in any scope below it.我对这个问题的解决方案是将
this
react 类的上下文存储到一个变量中,然后在它下面的任何范围内使用它。
fetchStock() {
const pointerToThis = this; // points to context of current react class
fetch(API_Call)
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(pointerToThis); // you can use pointerToThis which in turn points to react class
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.