【问题标题】:How do I update Reactjs State with data I retrieved using a fetch API call?如何使用我使用 fetch API 调用检索到的数据更新 Reactjs 状态?
【发布时间】: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


【解决方案1】:

我遇到了类似的问题。我对这个问题的解决方案是将 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 
  });
}

【讨论】:

    【解决方案2】:

    首先在构造函数中添加

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

    }

    【讨论】:

      【解决方案3】:

      因为您在安装组件后调用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 类来为fetchStock 提供适当的上下文,如下所示:

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

      或者有另一种方法来实现相同的(也许更清洁的方式):

      fetchStock = () => {
      
      }
      

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 1970-01-01
        • 2021-08-17
        • 1970-01-01
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        • 2015-05-10
        • 2023-01-23
        相关资源
        最近更新 更多