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 @ 2022-07-06 09:47  uxinxin  阅读(28)  评论(0编辑  收藏  举报