无法读取未定义的属性'setState'

问题描述 投票:0回答:1

我正在尝试使用flickr api来获取公共照片并使用它们创建图像轮播,但似乎它不想在开始时获取照片。由于我是React的新手,很难弄清楚我在这里做错了什么,所以任何帮助都会受到赞赏..谢谢。

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

上面的代码返回'TypeError:无法读取'undefined'属性'setState',我不太清楚这意味着什么..

javascript reactjs flickr
1个回答
4
投票

你在Promise的回调函数中调用setState()。

错误是因为这不是React组件。

您应该使用箭头函数或将React Component实例绑定到回调函数。

例如:

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

要么:

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));
© www.soinside.com 2019 - 2024. All rights reserved.