javascript - 使用 React 获取数组中的下一个/上一个项目

标签 javascript arrays reactjs

我对 React 和编程不太熟悉,我进行了搜索,只找到了非 React 特定的 js 解决方案。

无法显示通过 props 传递的数组中的下一个或上一个项目。单击“下一步”按钮时,我只看到数组中返回的相同项目而不是下一个项目,我知道上一个将返回 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/...""
 }  
]

最佳答案

错误:

1. 如果您在 for 循环中使用 return 关键字,它不会破坏 循环,它也会从该函数返回,所以在这些行中:

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

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

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

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

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

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

2. 单击“下一个”和“上一个”按钮时,增加或减少索引值,并使用该索引将状态视频数组的特定对象传递给子组件。

像这样:

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>
        )
    }
}

关于javascript - 使用 React 获取数组中的下一个/上一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44861092/

相关文章:

javascript - 用一个对象 react 状态钩子(Hook)

javascript - ReactJs/Typescript 如何将对象数组传递到界面 Prop 中?

javascript - 使用 xpath 和 nightwatch.js 单击动态文本

javascript - 将第二个参数传递给自动采用第一个参数的函数

javascript - 以下函数中加号 (+) 的作用是什么,该函数摘自 jquery 源代码

php - 获取对数组元素的引用,其中数组可以作为 $obj->$propName 访问

arrays - 无法从数组获取数据

javascript - 我的 X 轴没有呈现我想要的所有刻度 - D3 JS

javascript - 使用公共(public) API 访问(无 OAuth)从 JavaScript 写入 Google 电子表格

objective-c - 从 Objective-C 中的数组中消除连续重复项的最快方法