Set TimeOut to React Function

前端 未结 2 801
时光说笑
时光说笑 2021-01-21 20:34

I have the following object list:

mediaList[
 {id:1, url:\"www.example.com/image1\", adType:\"image/jpeg\"},
 {id:2, url:\"www.example.com/image2\", adType:\"ima         


        
相关标签:
2条回答
  • 2021-01-21 21:05

    If you want to change the media on every 5 seconds, you will have to update the state to re-render your components You can also use setInterval instead of setTimeout. setTimeout will be triggered only once, setInterval will be triggered every X milliseconds. Here what it may look like:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = { activeMediaIndex: 0 };
      }
    
      componentDidMount() {
        setInterval(this.changeActiveMedia.bind(this), 5000);
      }
    
      changeActiveMedia() {
        const mediaListLength = this.props.medias.length;
        let nextMediaIndex = this.state.activeMediaIndex + 1;
    
        if(nextMediaIndex >= mediaListLength) {
          nextMediaIndex = 0;
        }
    
        this.setState({ activeMediaIndex:nextMediaIndex });
      }
    
      renderSlideshow(){
        const ad = this.props.medias[this.state.activeMediaIndex];
        let adType = ad.adType;
        if(type.includes("image")){
          return(
            <div className="imagePreview">
              <img src={ad.url} />
            </div>
          );
        }else if (adType.includes("video")){
          return(
            <video className="videoPreview" controls>
                <source src={ad.url} type={adType}/>
              Your browser does not support the video tag.
            </video>
          )
    
        }
      }
    
      render(){   
        return(
          <div>
              {this.renderSlideshow()}
          </div>
        )
      }
    }
    

    Basically what the code is doing is that every 5 seconds, will change the activeMediaIndex to the next one. By updating the state, you will trigger a re-render. When rendering the media, just render one media (you can also render the previous one and the next one like a classic slideshow). Thus way, every 5 seconds, you will render a new media.

    0 讨论(0)
  • 2021-01-21 21:08

    Don't forget to clear the timeout to prevent memory leaks:

      componentDidMount() {
        this.timeout = setTimeout(() => {
         ...
        }, 300);
      }
    
      componentWillUnmount() {
        clearTimeout(this.timeout);
      }
    
    0 讨论(0)
提交回复
热议问题