我试图在React中创建一个闪光灯,然而,闪光灯本身以不一致的速率闪烁/渲染并且有点令人沮丧。请参阅附带的代码段。组件安装是否有问题?谢谢!
class Blinker extends React.Component {
constructor(props) {
super();
this.state = {
appear: true
}
this.blinker = this.blinker.bind(this);
}
blinker() {
this.setState({appear: !this.state.appear });
}
componentDidMount() {
setInterval(this.blinker, 1000)
}
componentDidUpdate() {
setTimeout(this.blinker, 1000)
}
render() {
return (
<div>
{ (this.state.appear) && "xxx" }
</div>
);
}
}
ReactDOM.render(
<Blinker />,
app
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
答案 0 :(得分:3)
删除componentDidUpdate
。为什么在组件更新后会触发新的一秒超时? didMount
的时间间隔仍在运行。
此外,您需要清除组件卸载时的间隔:
componentDidMount() {
this.blinkerId = setInterval(this.blinker, 1000)
}
componentWillUnmount() {
clearInterval(this.blinkerId);
}