简体   繁体   English

如何使用我使用 fetch API 调用检索到的数据更新 Reactjs 状态?

[英]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.

相关问题 如果我不应该在componentWillUpdate中调用setState,如何更新状态(使用ReactJS)? - How do I update the state (using ReactJS) if I should not call setState in componentWillUpdate? ReactJS:异步API数据提取完成后,我无法获得使用API​​数据更新的状态 - ReactJS: I can not get the state to update with API data when the asynchronous API data fetch is completed 从Firebase检索数据后,如何异步调用提取 - How do I asynchronously call fetch after data from the Firebase has been retrieved 如何从 ReactJS 的提取中设置 state? - How do I set state from within a fetch in ReactJS? 在对 API 进行 fetch 调用后,如何将数据存储到 localStorage? - How do I store data into localStorage after a fetch call to an API? 我如何获取 get api 调用的数据,格式为 reactjs 中 object 数组中的 object 嵌套数组? - How can i fetch the data of an get api call which is in the format as nested array of object in array of object in reactjs? ReactJS-如何更新嵌套和“正常”状态属性? - ReactJS - how do I update nested and “normal” state properties? 如何使用 reactjs 从多个 API 获取搜索结果 - How do I fetch search results from multiple API using reactjs ReactJS:如何使用localStorage更新属性状态? - ReactJS: How can I update state of property using localStorage? 我如何在ReactJS中更新提取请求 - How can i update fetch request in reactjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM