我有一个无法在 React 中解决的问题:我想每 3 秒更改一次背景图像。代码可以做到这一点,但它只涉及一个问题:当我更新“teaserAnimCount”状态时,我可以在控制台中看到该值呈指数增长。不知道为什么,时间长了,就出现问题了,因为web小哥崩溃了。
一开始,“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;
感谢您的帮助。
最佳答案
看起来它是从渲染中调用 this.renderTeaserBackground() ,该函数更新状态,并调用调用状态更新的渲染等。由于超出了最大调用堆栈,它崩溃了。
我会尝试移动 this.renderTeaserBackground();调用 componentWillMount() 并仅使用渲染函数内的状态变量。
关于javascript - 在react.js中每3秒更改一次图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49202949/