Reactjs:如何遍历组件中的对象数组?

时间:2015-12-03 05:44:44

标签: reactjs

以下是我要做的事情:

我有一个api会返回一组JSON对象(来自TMdb的热门电影),我想一次显示1部电影(标题和海报图片),然后是" next"单击按钮显示阵列中的下一部电影。

这是我的反应组件,它按预期工作,但我觉得我没有以正确的方式做到这一点。非常感谢任何见解。

var PopularMovies = React.createClass({
getInitialState: function() {
    return {
        title: '',
        posterUrl: '',
        index: 0
    };
},

nextMovie: function() {
    var index = this.state.index;
    index++;

    var movie = this.state.movies[index];

    this.setState({
        index: index,
        title: movie.title,
        posterUrl: 'http://cf2.imgobject.com/t/p/w154/' + movie.poster_path
    });
},

componentDidMount: function() {

    $.get('http://localhost:3000/api/v1/popular_movies', function(res) {
        if (this.isMounted()) {
            this.setState({
                movies: res,
                title: res[this.state.index].title,
                posterUrl: 'http://cf2.imgobject.com/t/p/w154/' + res[this.state.index].poster_path
            });
        }
    }.bind(this));
},

render: function() {
    return (
        <div>
            <img src={this.state.posterUrl} />
            <h3>{this.state.title}</h3>
            <button onClick={this.nextMovie}>Next</button>
        </div>
    );
}
});

0 个答案:

没有答案