2016-11-28 105 views
1

國家是不會得到更新

這裏是我的index.js

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

import Photo from './components/photo'; 

const urlArr = []; 
const apiKey = "API"; 
const userId = "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((photoData) => { 
     _.forEach(photoData.data.photos.photo, (photo) => { 
     urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`); 
     }); 
     this.setState({ urlArr }); 
    }); 
    } 

    render() { 
    return (
     <div> 
     <Photo urls={this.state.urlArr}/> 
     </div> 
    ); 
    } 
}; 

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

,這裏是我的photo.js

import React, { Component } from 'react'; 
import NextButton from './nextButton'; 
import PrevButton from './prevButton'; 

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

    this.state = { idx: 0 }; 
    this.nextImg = this.nextImg.bind(this); 
    } 

    nextImg() { 
    this.setState({ idx: this.state.idx++ }); 
    } 

    render() { 
    if (this.props.urls.length === 0) { 
     return <div>Image Loading...</div> 
    } 

    console.log(this.state); 
    return(
     <div> 
     <PrevButton /> 
     <img src={this.props.urls[this.state.idx]}/> 
     <NextButton onClick={this.nextImg}/> 
     </div> 
    ); 
    } 
} 

export default Photo; 

和我nextButton.js(同prevButton.js

import React from 'react'; 

const NextButton =() =>{ 
    return (
    <div> 
     <button>next</button> 
    </div> 
); 
}; 

export default NextButton; 

因爲我是相當新的陣營,我不明白爲什麼當我點擊下一個按鈕我this.state.idx沒有得到更新(在我看來,它甚至不是射擊nextImg函數或者)。如果任何人都可以給我一個幫助或建議,那真的很感激。

在此先感謝!

+0

當你點擊該按鈕,您應該檢查是否'nextImg'炒魷魚 – Khang

回答

1

更新您的NextButton。在演示組件中使用該事件。

<NextButton next={this.nextImg}/> 

NextButton組件應該看起來像這樣。

import React from 'react'; 
const NextButton = (props) =>{ 
return (<div> 
    <button onClick={props.next}>next</button> 
    </div> 
); 
}; 
+0

對不起,它不work..and我想this.nextImg = this.nextImg在我的構造函數中綁定(this)正在照顧那個..不確定tho .. – ckim16

+0

'nextImg'的上下文已經在構造函數 – Khang

+0

中綁定,它仍然不會更新我的狀態。但是,無論何時點擊「下一個」,它都會將道具記錄爲空對象。 – ckim16

1

問題在於這一段代碼:

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

thisaxios.get回調範圍,而不是組件。您可以定義另一個名爲self的變量,或者對您更有意義的變量,並致電self.setState()

了類似的問題,請參見該問題:Javascript "this" scope