使用react获取下一个/数组中的上一个项目

时间:2017-07-01 12:45:04

标签: javascript arrays reactjs

我是新手一般的反应和编程,我搜索过,只发现js的解决方案没有特定的反应。

在通过道具传递的数组中显示下一个或上一个项目时遇到问题。当单击“下一步”按钮时,我只看到返回的数组中的相同项目而不是下一个项目,我理解之前将返回null作为加载时显示第一个项目。

import React, { Component } from 'react'
import VideoPlayer from './Video'
import axios from 'axios'

export default class App extends Component {
constructor(props) {
super(props);

this._TogglePrev = this._TogglePrev.bind(this);
this._ToggleNext = this._ToggleNext.bind(this);

// app state
this.state = {
videos: [],
selectedVideo: null
 }
}

componentDidMount() {
   axios.get('http://localhost:5000/v1/video?id=287948764917205')
   .then((result)=> {
     var videos = result.data.payload
     this.setState({
       videos: videos,
       selectedVideo: videos[0]
     });
   })
 }

componentWillUnmount() {
 this.serverRequest.abort()
 }

// State transitions
  _ToggleNext() {
    console.log("something worked");
    // take a copy of our state
    const selectedVideo = this.state.selectedVideo;
    // next video
    var i = 0,
    max = selectedVideo.length;
    for (i; i < max; i += 1) {
        if (selectedVideo[i]) {
            return selectedVideo[i + 1];
        }
    }
    //set our state
    this.setState( selectedVideo );
    console.log(selectedVideo)
  }

  _TogglePrev() {
    console.log("something worked");
    var current = this.state.selectedVideo;
    var prev = current - 1;
    if (prev < 0) {
      prev = this.state.videos.length - 1;
    }
    // update our state
    this.setState({ prev });
  }

 render() {
  return (
     <div className="App" style={{width: '100%', height: '100%'}}>
       <div className="controls">
         <button className="toggle toggle--prev" onClick={this._TogglePrev}>Prev</button>
         <button className="toggle toggle--next" onClick={this._ToggleNext}>Next</button>
       </div>
        <VideoPlayer video={this.state.selectedVideo} />
     </div>
  )
 }
}

返回的数据

[
 {  eventId: "287948764917205"
  userName: "Jon Doe"
  videoLink: "https://"https:s3.amazonaws.com/...""
  userPhotoLink: "https://"https:s3.amazonaws.com/...""
 },
 { eventId: "287948764917205"
 userName: "Jane Thompson"
 videoLink: "https://"https:s3.amazonaws.com/...""
 userPhotoLink: "https://"https:s3.amazonaws.com/...""
 }  
]

2 个答案:

答案 0 :(得分:4)

<强>错误:

1。如果您在return循环中使用for关键字,则 <**>会突破loop,它将返回从这个函数也是如此,所以在这些行中:

for (i; i < max; i += 1) {
    if (selectedVideo[i]) {
        return selectedVideo[i + 1];
    }
}
this.setState( selectedVideo );
....

如果if(selectedVideo[i])将返回true,那么它将中断循环并从函数返回,因此该for循环之后的行将永远不会执行,因为返回语句。

2。 setState是一个函数,我们需要在此传递一个object(键值对,键将是状态变量名),所以你需要像这样写:

this.setState({ selectedVideo }); or this.setState({ selectedVideo: selectedVideo });  //both are same

通过维护索引编写代码的另一种方式

1。而不是在状态变量中维护selectedVideo而不是仅维护索引,数组项的索引。

2. 点击next和prev按钮,增加或减少索引值,并使用该索引将状态视频数组的特定对象传递给子组件。

像这样:

import React, { Component } from 'react'
import VideoPlayer from './Video'
import axios from 'axios'

export default class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            videos: [],
            selectedIndex: 0
        }
        this._TogglePrev = this._TogglePrev.bind(this);
        this._ToggleNext = this._ToggleNext.bind(this);
    }

    componentDidMount() {
        axios.get('http://localhost:5000/v1/video?id=287948764917205')
        .then((result)=> {
            var videos = result.data.payload
            this.setState({
                videos: videos,
                selectedIndex: 0
            });
        })
    }

    componentWillUnmount() {
        this.serverRequest.abort()
    }

    _ToggleNext() {
        if(this.state.selectedIndex == this.state.videos.length - 1)
            return;

        this.setState(prevState => ({
            selectedIndex: prevState.selectedIndex + 1
        }))
    }

    _TogglePrev() {
        if(this.state.selectedIndex == 0)
         return;

        this.setState(prevState => ({
            selectedIndex: prevState.selectedIndex - 1
        }))
    }

    render() {
        let {selectedIndex, videos} = this.state;
        return (
             <div className="App" style={{width: '100%', height: '100%'}}>
                  <div className="controls">
                    <button className="toggle toggle--prev" onClick={this._TogglePrev}>Prev</button>
                    <button className="toggle toggle--next" onClick={this._ToggleNext}>Next</button>
                  </div>
                  <VideoPlayer video={videos[selectedIndex]} />
             </div>
        )
    }
}

答案 1 :(得分:0)

最好在构造函数中编写:

    constructor(props) {
    super(props);

    this._TogglePrev.bind(this);
    this._ToggleNext.bind(this);

    // app state
    this.state = {
    videos: [],
    selectedVideo: null,
selectedVideoIndex:0
     }
    }

并且还要改变

 _ToggleNext() {
    console.log("something worked");
    // take a copy of our state
    const selectedVideo = this.state.selectedVideo;
    // next video
    var selectedVideoIndex = this.state.selectedVideoIndex; //i always starts with zero ????? you need also to save the index

    max = selectedVideo.length;
    for (selectedVideoIndex; selectedVideoIndex < max; selectedVideoIndex++) {
        if (selectedVideo[selectedVideoIndex]) {
            const retval = selectedVideo[selectedVideoIndex + 1];
            this.setState( selectedVideoIndex+1 );
            this.setState(retval  );
            return retval;
        }
    }


    console.log(selectedVideo)
  }