react 16.8.4版本中的生命周期中的细节 在组件挂在时使用了定时器的处理——尚硅谷React教程(2022加更,B站超火react教程)学习笔记

react 16.8.4版本中

如果页面加载时要挂在一个定时器,且里面在修改状态,一定不能写在render里面,需要写到生命周期函数 componentDidMount中,否则会导致循环更新页面状态反复调用render造成死循环

另外定时器的卸载可以统一放在componentWillUnmount里面进行处理,这样代码更合理,思路更清晰

复制代码
 1         class Life extends React.Component {
 2             state={opacity:1}
 3             death=()=>{
 4                 clearInterval(this.timer)
 5                 ReactDOM.unmountComponentAtNode(document.querySelector('#test'))
 6             }
 7             componentDidMount() {
 8                 this.timer=setInterval(() => {
 9                     let {opacity}=this.state
10                     opacity-=0.1
11                     if(opacity<=0) opacity=1
12                     this.setState({opacity})
13                 }, 200);
14             }
15             render() {
16                 console.log('render')
17                 const {opacity}=this.state
18                 return (
19                     <div>
20                         <h1 style={{opacity:opacity}}>React学不会怎么办</h1>
21                         <button onClick={this.death}>不活了</button>
22                     </div>
23                 )
24             }
25         }
26         ReactDOM.render(<Life />,document.querySelector('#test'))
复制代码

 

复制代码
 1         class Life extends React.Component {
 2             state={opacity:1}
 3             death=()=>{
 4                 ReactDOM.unmountComponentAtNode(document.querySelector('#test'))
 5             }
 6             componentDidMount() {
 7                 this.timer=setInterval(() => {
 8                     let {opacity}=this.state
 9                     opacity-=0.1
10                     if(opacity<=0) opacity=1
11                     this.setState({opacity})
12                 }, 200);
13             }
14             
15             componentWillUnmount(){
16                 clearInterval(this.timer)
17             }
18             render() {
19                 console.log('render')
20                 const {opacity}=this.state
21                 return (
22                     <div>
23                         <h1 style={{opacity:opacity}}>React学不会怎么办</h1>
24                         <button onClick={this.death}>不活了</button>
25                     </div>
26                 )
27             }
28         }
29         ReactDOM.render(<Life />,document.querySelector('#test'))
复制代码

 

posted @   uxinxin  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示