[英]Change image each 3 seconds in react.js
我有一個無法解決的問題:我想每3秒更改一次背景圖像。 代碼可以做到這一點,但是它只涉及一個問題:當我更新“ teaserAnimCount”狀態時,我可以在控制台中看到該值呈指數增長。 我不知道為什么隨着時間的流逝會出現問題,因為網絡兄弟崩潰了。
首先,“ console.log(” this.state.teaserAnimCount“)的值是1(很好),然后是3,然后是7,然后是15,...如果您知道為什么?
這在renderTeaserBackground箭頭函數中。
我的代碼:
import React, { Component } from 'react';
import teaserImg1 from '../img/teaser-img-1.png';
import teaserImg2 from '../img/teaser-img-2.png';
import teaserImg3 from '../img/teaser-img-3.png';
import teaserImg4 from '../img/teaser-img-4.png';
import ProjetTitle from './ProjetTitle';
import { HashLink as Link } from 'react-router-hash-link';
import { TweenMax, Linear } from 'gsap';
import '../plugins/DrawSVGPlugin';
const teaserBgImg = [teaserImg1, teaserImg2, teaserImg3, teaserImg4];
class Teaser extends Component {
constructor(props) {
super(props);
this.state = {
teaserAnimDuration: 3,
teaserBg: teaserBgImg,
teaserAnimCount: 0,
teaserBgLength: teaserBgImg.length,
teaserBackground: ''
}
}
componentDidMount() {
TweenMax.from(
this.refs.circle,
this.state.teaserAnimDuration,
{
drawSVG: "0%",
ease: Linear.easeNone,
repeat: -1
}
)
}
renderTeaserBackground = () => {
setTimeout(function() {
let teaserBackground = this.state.teaserBg[this.state.teaserAnimCount];
this.setState({teaserAnimCount: this.state.teaserAnimCount + 1});
this.setState({teaserBackground});
console.log(this.state.teaserAnimCount);
}.bind(this), this.state.teaserAnimDuration * 1000);
return this.state.teaserBackground;
}
render() {
this.renderTeaserBackground();
let backgroundImg = {
backgroundImage: 'url(' + this.state.teaserBackground + ')'
}
return (
<Link to="/Content" className="teaser" style={backgroundImg}>
<svg className="svg-teaser" xmlns="http://www.w3.org/2000/svg">
<circle ref="circle" cx="50%" cy="50%" r="50%" fill="none"/>
</svg>
<div className="teaser-text-container flex">
</div>
<ProjetTitle className="teaser-info-teaser"/>
</Link>
);
}
}
export default Teaser;
謝謝您的幫助。
看起來好像是從render調用this.renderTeaserBackground(),此函數更新狀態,並調用調用狀態更新的render等。由於超出了最大調用堆棧數,它崩潰了。
我會嘗試移動this.renderTeaserBackground(); 調用componentWillMount()並僅使用render函數中的狀態變量。
夫妻的事。
render
調用this.setState
(調用另一個調用它的函數)。 如果要在渲染之前運行某些內容,請使用componentWillMount
。 如果要在渲染后立即運行,請使用componentDidMount
。 該文檔建議將componentDidMount
用於更改狀態的操作(盡管我認為這不是硬性規定)。 this.setState
的回調形式。 參數是一個回調,可為您提供當前狀態。 這是一個涵蓋我大部分觀點的工作示例: https : //jsfiddle.net/69z2wepo/130855/
首次加載組件時,它會調用render
函數,后者會調用renderTeaserBackground
函數。
renderTeaserBackground
函數修改組件的state
,迫使組件再次重新渲染,執行render
, renderTeaserBackground
再次執行renderTeaserBackground
函數。 等等 ...
將this.renderTeaserBackground
從render
功能移動到componentDidMount
生命周期掛鈎。
在setTimeout
回調函數中添加另一個對renderTeaserBackground
調用,或使用setInterval
。
刪除此行, return this.state.teaserBackground;
。 沒用的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.