2016-11-27 165 views
0

我試圖使用flickr API來獲取公開照片並創建一個圖像旋轉木馬,但似乎並不想在開始時獲取照片。由於我是React新手,很難弄清楚我在這裏做錯了什麼,所以任何幫助將不勝感激。謝謝。無法讀取未定義的屬性'setState'

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

以上代碼返回「類型錯誤:無法讀取屬性‘的’未定義」的setState,我不太清楚這是什麼意思..

回答

3

你調用的setState()回調函數Promise

錯誤是因爲這個不是React組件。

您應該使用箭頭函數或將React組件實例綁定到回調函數。

例如:

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)); 
+0

噢,我的上帝,它的作品!非常感謝!! – ckim16

相關問題