javascript - Changing an Image on in time interval using react - Stack Overflow

I am trying to change the image displayed every 1 second the first image appears then switches to the a

I am trying to change the image displayed every 1 second the first image appears then switches to the alt display and does not continue switching the pictures

export default class Slideshow extends Component {

    constructor(props) {
        super(props);
        this.getImageId = this.getImageId.bind(this);
        this.switchImage = this.switchImage.bind(this);
        this.init = this.init.bind(this);
        this.state = {
            currentImage: 0,
            image: 0

        };
    }

    getImageId() {
        if(this.currentImage < 3) {
            this.setState({
                currentImage: this.state.currentImage +1
            })
        } else {
            this.setState({
                currentImage: 0
            })
        }
        return this.currentImage;
    }

    switchImage() {
            this.setState({
                image: this.getImageId()
            });
    }

    init() {
        setInterval(this.switchImage, 1000)
    }


    render() {
        const imagePath = [guy, girl, wash, swifer];
        this.init();

        return (
            <div className="slideshow-container">
                <img src={imagePath[this.state.image]} alt="cleaning images"/>      
            </div>
        );
    }
}

Pictures will switch every 1 seconds to the next picture in the array and go back to original after going through whole array

I am trying to change the image displayed every 1 second the first image appears then switches to the alt display and does not continue switching the pictures

export default class Slideshow extends Component {

    constructor(props) {
        super(props);
        this.getImageId = this.getImageId.bind(this);
        this.switchImage = this.switchImage.bind(this);
        this.init = this.init.bind(this);
        this.state = {
            currentImage: 0,
            image: 0

        };
    }

    getImageId() {
        if(this.currentImage < 3) {
            this.setState({
                currentImage: this.state.currentImage +1
            })
        } else {
            this.setState({
                currentImage: 0
            })
        }
        return this.currentImage;
    }

    switchImage() {
            this.setState({
                image: this.getImageId()
            });
    }

    init() {
        setInterval(this.switchImage, 1000)
    }


    render() {
        const imagePath = [guy, girl, wash, swifer];
        this.init();

        return (
            <div className="slideshow-container">
                <img src={imagePath[this.state.image]} alt="cleaning images"/>      
            </div>
        );
    }
}

Pictures will switch every 1 seconds to the next picture in the array and go back to original after going through whole array

Share Improve this question edited Jul 19, 2019 at 7:50 Aksen P 4,5993 gold badges15 silver badges27 bronze badges asked Jul 19, 2019 at 7:33 Justin AliaJustin Alia 311 gold badge1 silver badge2 bronze badges 1
  • Hi Justin, I just provided you a solution below, that should give you enough insight on how to integrate this feature. Let me know if you have any questions, and please consider upvoting and marking it as the answer :) – Cat_Enthusiast Commented Jul 19, 2019 at 18:07
Add a ment  | 

2 Answers 2

Reset to default 6

Try something like this instead: https://codesandbox.io/s/naughty-sara-q3m16

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.switchImage = this.switchImage.bind(this);
    this.state = {
      currentImage: 0,
      images: [
        "https://images.unsplash./photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
        "https://img.purch./w/660/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNC84MzAvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzExMTA1NzIxNTkuanBn",
        "https://d17fnq9dkz9hgj.cloudfront/uploads/2012/11/152964589-wele-home-new-cat-632x475.jpg",
        "https://i.ytimg./vi/jpsGLsaZKS0/maxresdefault.jpg"
      ]
    };
  }

  switchImage() {
    if (this.state.currentImage < this.state.images.length - 1) {
      this.setState({
        currentImage: this.state.currentImage + 1
      });
    } else {
      this.setState({
        currentImage: 0
      });
    }
    return this.currentImage;
  }

  ponentDidMount() {
    setInterval(this.switchImage, 1000);
  }

  render() {
    return (
      <div className="slideshow-container">
        <img
          src={this.state.images[this.state.currentImage]}
          alt="cleaning images"
        />
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

We can simplify your code by doing a couple of things:

  1. Put the images-array in the state, so that we can iterate over the image-paths and keep track of the current images index.
  2. So now we can consolidate switchImage and getImageId into a single function that serves the same purpose. We just check the currentImage (index) against the length of the array.
  3. React also has a life-cycle method called ponentDidMount() which executes logic right after a ponent is rendered the first-time. I used this to replace the init() function. There is an issue with calling init() in render(). Every time a ponent re-renders, it executes the logic in render(), which means you would be creating a new setInterval() on every subsequent re-render. ponentDidMount() only triggers a single time, making it perfect for defining intervals.

The main issue with your code is that you called init function with in render function, whenever state get update render executes as well, so init function call again and again each time render function execute

the solution is to set intervals in ponentDidMount function

ponentDidMount run only one time after ponent mount in the DOM, for help related to react life cycle function do visit the official documentation

https://reactjs/docs/react-ponent.html

also have a look this post image

https://reactjs/docs/react-ponent.html

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742331953a4423896.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信