1.setState()不能写在render()内。
2.setInterval()等函数不能随意写在class内render外。
3.对象key与value相同会触发简写机制。{opacity:opacity}等同于{opacity}
4.生命周期函数无需写成箭头函数形式。
class Life extends React.Component{
state={opacity:1}
render(){
return (<div>
<h1 style={{opacity:this.state.opacity}}>生命周期</h1>
<button onClick={this.death}>不活了</button>
</div>)
}
componentDidMount(){
this.timer=setInterval(()=>{
let {opacity}=this.state
opacity-=0.1
if(opacity<=0)opacity=1;
this.setState({opacity:opacity})
},200)
}
componentWillUnmount(){
clearInterval(this.timer)
}
death=()=>{
卸载组件
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
}
ReactDOM.render(<Life/>,document.getElementById('test'))
5.初始化阶段: 由ReactDOM.render()触发---初次渲染
1. constructor()
2. componentWillMount()
3. render()
4. componentDidMount() =====> 常用
一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息
6.更新阶段: 由组件内部this.setSate()或父组件render触发
1. shouldComponentUpdate()=====>控制组件更新的“阀门”,返回true or false,默认返回true
2. componentWillUpdate()
3. render() =====> 必须使用
4. componentDidUpdate()
7. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
1. componentWillUnmount() =====> 常用
一般在这个钩子中做一些收尾的事,例如:关闭定时器、取消订阅消息