简体   繁体   中英

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. 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.

The object in pricesArr prints in the console and looks like this:

[{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. 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})
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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