Set TimeOut to React Function

前端 未结 2 803
时光说笑
时光说笑 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(
            
    ); }else if (adType.includes("video")){ return( ) } } render(){ return(
    {this.renderSlideshow()}
    ) } }

    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.

提交回复
热议问题