Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Cambiando el setinterval de la imagen de fondo solo llamando una vez

Esto está en REACT.JS. He revisado las diferentes publicaciones aquí tratando de encontrar una solución, sin embargo, no he podido hacer que esto se ejecute más de una vez. Cualquier idea sería muy apreciada! Tengo el código del componente a continuación.

 import React, { Component } from 'react' import './Login.css' import LoginHousing from './LoginHousing' import bg1 from '../../images/backgrounds/lawn-maintenance.jpg' import bg2 from '../../images/backgrounds/body-shop.jpg' import bg3 from '../../images/backgrounds/mechanic.jpg' import bg4 from '../../images/backgrounds/painting.jpg' import bg5 from '../../images/backgrounds/hair-stylist.jpg' export default class Login extends Component { constructor(){ super() this.state = {loginBg: bg1} } // Background slideshow effect on mount, changing every 2 seconds changingBackground() { let i = 0 const images = [bg1, bg2, bg3, bg4, bg5] if (i < images.length - 1) { i++; } else { i = 0; } this.setState({loginBg: images[i]}) } componentDidMount() { this.timer = setInterval( () => this.changingBackground(), 2000 ); } componentWillUnmount(){ clearInterval(this.timer) } render() { return ( <div className='login vw-100 vh-100' style={{backgroundImage: `url(${this.state.loginBg})`}}> <LoginHousing /> </div> ) } }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

let i = 0

Esta variable es local para la función, por lo que cada vez que se ejecuta esa función en el intervalo, básicamente comienza desde el principio .


Podrías cambiar el código a esto:

 changingBackground() { this.setState((ps) => { return { index: (ps.index + 1) % this.images.length, // store images in instance field }; }); }

Y luego renderizar:

 this.images[this.state.index]

PD y constructor:

 constructor() { super(); this.state = { index: 0 }; }
about 4 years ago · Juan Pablo Isaza Report

0

Te daré una pequeña explicación antes de la solución para esto, porque cuando llamas a this.changingBackground() siempre volverá a cero , como ves en la primera declaración de let i = 0 , por lo que cada vez que la función se ejecuta será cero, creo que la mejor solución para esto es hacer que el contador de las imágenes de fondo sea una variable de estado :

 import React, { Component } from 'react'; export default class Login extends Component { constructor(){ super(); this.state = {loginBg: bg1, indexImage: 0} } changingBackground() { const images = [bg1, bg2, bg3, bg4, bg5] if (indexImage < images.length - 1) { this.setState({indexImage: this.state.indexImage + 1}); } else { this.setState({indexImage: 0}); } this.setState({loginBg: images[this.state.indexImage]}); } componentDidMount() { this.timer = setInterval( () => this.changingBackground(), 2000 ); } componentWillUnmount(){ clearInterval(this.timer); } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!