2016-11-28 49 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