如何使用通过访存API调用检索到的数据更新Reactjs State?

时间:2019-07-17 05:59:10

标签: javascript reactjs api state prop

我在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”。

谢谢您的帮助!

3 个答案:

答案 0 :(得分:1)

由于在安装组件后正在调用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 = () => {

}

或者还有另一种方法可以达到相同目的(也许更干净):

[ Front-End ]
const inOneHour = moment()
  .add(1, 'hours')
  .format('MMMM Do YYYY, HH:mm:ss');


[ users table / Database ]
table.datetime('resetPasswordExpires', { useTz: false });

答案 1 :(得分:1)

首先在构造函数内部添加

const mapDispatchToProps = (dispatch: any) => ({
  getProducts: () => dispatch(productActions.getProducts()),
  saveProduct: (ids: number[]) => dispatch(productActions.saveProduct(ids)),
});

像这样更新fetchStock函数:

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

}

答案 2 :(得分:1)

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

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