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

How do I update Reactjs State with data I retrieved using a fetch API call?

我在 react.js 中进行了提取 API 调用,并将其放入包含提取函数的函数中定义的变量中。但是我如何将这个值转移到状态中的变量之一呢?我可以到达 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' .

感谢您的帮助!

因为您在安装组件后调用 fetchStock。您可以按如下方式使用箭头功能。

.then((data) => {
   // use data here
   this.setState({ ... }) // set you state
})

或者如果您不习惯使用箭头函数,那么我相信您可以创建一个函数来处理承诺,例如handleData

.then(this.handleData)

在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() {}
}

如果您在用户操作中调用 fetchStock,例如单击按钮,那么您可以通过将其绑定到您创建的 React class 来为 fetchStock 提供适当的上下文如下:

constructor() {
  this.fetchStock = this.fetchStock.bind(this);
}

或者有另一种方法可以达到同样的目的(也许是更简洁的方法):

fetchStock = () => {

}

首先在构造函数中添加

this.fetchStock = this.fetchStock.bind(this);

像这样更新 fetchStock 函数:

fetchStock() {
  const API_KEY = 'api key goes here';
  let TimeInterval = '60min';
  let StockSymbol = 'AMZN';
  let API_Call = `https://www.alphavantage.co/queryfunction=TIME_SERIES_INTRADAY&symbol=${StockSymbol}&interval=${TimeInterval}&outputsize=compact&apikey=${API_KEY}`;

  let stockHistoryDatabase = {};
  let stockHistoryDatabaseString;

  fetch(API_Call)
    .then(response => response.json())
    .then(data => {
      for (var key in data['Time Series (60min)']) {
        var epochKeyTime = new Date(key);
        epochKeyTime = epochKeyTime.getTime();
        stockHistoryDatabase[epochKeyTime] = data['Time Series (60min)'][key]['1. open'];
      }
    this.setState({stockInfo: stockHistoryDatabase}) 
    //Set your state here.

    stockHistoryDatabaseString = JSON.stringify(stockHistoryDatabase);
  }
  );

}

我遇到了类似的问题。我对这个问题的解决方案是将 this react class 的上下文存储到一个变量中,然后在它下面的任何范围内使用它。

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 
  });
}