我有一个无法在 react 中解决的问题:我想每 3 秒更改一个背景图像。代码可以做到这一点,但它只涉及一个问题:当我更新"teaserAnimCount"状态时,我可以在我的控制台中看到这个值呈指数级增长。我不知道为什么,随着时间的推移,这是一个问题,因为网络兄弟崩溃了。
一开始,"console.log("this.state.teaserAnimCount"(的值是1(很好(,然后是3,然后是7,然后是15,...如果你知道为什么?
这是在渲染预告片背景箭头函数中。
我的代码 :
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(( 并只在渲染函数中使用状态变量。
几件事。
- 如前所述,不要在
render
中调用this.setState
(调用另一个调用它的函数计数(。如果要在渲染之前运行某些内容,请使用componentWillMount
。如果您希望在渲染后立即运行某些内容,请使用componentDidMount
。文档建议将componentDidMount
用于更改状态的操作(尽管我认为这不是硬性规定(。 - 当您将状态更改为依赖于先前值的值时,最好使用
this.setState
的回调形式。参数是一个回调,它为您提供当前状态。 - 使用超时时,请确保仅在上一次超时中创建另一个超时。这将防止多个超时同时处于"活动状态"。
- 保留对超时的引用,并在组件卸载时将其清除。
这是一个涵盖我大部分观点的工作示例: https://jsfiddle.net/69z2wepo/130855/
当组件首次加载时,它会调用render
函数,该函数调用renderTeaserBackground
函数。
renderTeaserBackground
函数修改组件的state
,强制组件再次重新渲染,它会执行render
并再次执行renderTeaserBackground
函数。 等等...
将this.renderTeaserBackground
从render
函数移动到componentDidMount
生命周期挂钩。
在回调函数中添加另一个调用setTimeout
renderTeaserBackground
或使用setInterval
。
删除此行return this.state.teaserBackground;
. 没用。