简体   繁体   English

对象在控制台中打印,但不能使用它设置状态-ReactJS

[英]Object prints in the console but can't use it to set state - ReactJS

I'm making a request to an API for prices of a cryptocurrency for a date range & storing the result in an array. 我正在向API请求一个日期范围内的一种加密货币的价格,并将结果存储在一个数组中。 The goal is to populate a line graph with those prices when the page loads but I can't figure out for the life of my why pricesArr prints when I console.log it but if I try this.setState({dataArr: pricesArr}) then I get an TypeError: Cannot read property 'setState' of undefined. 目标是在页面加载时用这些价格填充折线图,但是当我在console.log pricesArr时我无法弄清楚为什么pricesArr打印,但是如果我尝试this.setState({dataArr: pricesArr})然后我得到一个TypeError: Cannot read property 'setState' of undefined.

The object in pricesArr prints in the console and looks like this: pricesArr中的对象将在pricesArr打印,如下所示:

[{USD: 7629.4, EUR: 6503.14}, {USD: 6754.4, EUR: 5432.14} ... ]



class App extends Component {

    constructor(props) {
    super(props);
    this.state = {
      dataArr:[]

     }
   }


  getData(){

    var url = 'https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD,EUR&ts='

    let pricesArr = []
    for (let i=1; i <= 30; i++) {
      const num = i.toString()
      const date = new Date('2018.06.' + num)
      const unixTimestamp = date / 1000
      const api_url = url + unixTimestamp

      if (i % 5 === 0 || i === 1) {
        axios.get(api_url)
        .then(res => {
            var obj = res.data['BTC']
            pricesArr.push(obj)
        })
      }
    }

    this.setState({dataArr: pricesArr})
  }

  componentDidMount () {
    this.getData()
  }


  render() {
    return (
      <div>
        Hi
      </div>
    );
  }
}

export default App;

Strange that your this is undefined. 奇怪的是您的this是不确定的。 try this. 尝试这个。

  getData = () => {

    var url = 'https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD,EUR&ts='

    let pricesArr = []
    for (let i=1; i <= 30; i++) {
      const num = i.toString()
      const date = new Date('2018.06.' + num)
      const unixTimestamp = date / 1000
      const api_url = url + unixTimestamp

      if (i % 5 === 0 || i === 1) {
        axios.get(api_url)
        .then(res => {
            var obj = res.data['BTC']
            pricesArr.push(obj)
        })
      }
    }

    this.setState({dataArr: pricesArr})
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM