简体   繁体   中英

Cannot read property 'setState' of undefined

I'm trying to use flickr api to fetch public photos and create an image carousel with them but seems it does not want to get photos in the beginning. Since I'm new to React, it is really hard to figure out what I'm doing wrong here so any kinda help will be appreciated.. Thank you.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import _ from 'lodash';

import Button from './components/button';

const urlArr = [];
const apiKey = "YOUR_API";
const userId = "YOUR_ID";
const url = `https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=${apiKey}&user_id=${userId}&format=json&nojsoncallback=1`;


class App extends Component {
  constructor(props) {
    super(props);

    this.state = { urlArr: [] };

    axios.get(url)
    .then(function(photoData) {
      _.forEach(photoData.data.photos.photo, (photo) => {
        // this.setState({ urlArr: `https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg` });
        urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`);
      });
      this.setState({ urlArr });
    });
  }

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

ReactDOM.render(<App/>, document.querySelector('.container'));

Code above returns 'TypeError: Cannot read property 'setState' of undefined' and I'm not quite sure what that means..

You're calling the setState() in a callback function of a Promise .

The error is because the this is not the React Component.

You should use an arrow function or bind the React Component instance to your callback function.

For example:

axios.get(url)
.then((photoData) => {
  _.forEach(photoData.data.photos.photo, (photo) => {
    // this.setState({ urlArr: `https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg` });
    urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`);
  });
  this.setState({ urlArr });
});

Or:

axios.get(url)
.then(function(photoData) {
  _.forEach(photoData.data.photos.photo, (photo) => {
    // this.setState({ urlArr: `https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg` });
    urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`);
  });
  this.setState({ urlArr });
}.bind(this));

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