1.1组件生命周期概述
1.2生命周期的三个阶段
1.3创建时(挂载阶段)
- class App extends React.Component{
- constructor(props){
- super(props)
- console.warn('生命周期钩子函数:constructor')
- }
- state={
- count:0
- }
- componentDidMount(){
- console.warn('生命周期钩子函数:componentDidMount')
- }
- render(){
- console.warn('生命周期钩子函数:render')
- // this.setState({
- // count:2
- // }) //会造成递归渲染
- return(
- <div>
- <h1>统计豆豆被打的次数:h1>
- <button>打豆豆button>
- div>
- )
- }
- }
- ReactDOM.render(<App/>,//调用的是父组件
-
- document.getElementById('root'))
递归渲染报错截图:
1.4更新时
- class App extends React.Component{
- constructor(props){
- super(props)
- }
- state={
- count:0
- }
-
- handleClick=()=>{
- this.setState({
- count:this.state.count+1
- })
- }
-
- render(){
- console.warn('生命周期钩子函数:render')
- // this.setState({
- // count:2
- // }) //会造成递归渲染
- return(
- <div>
- {/* <h1>统计豆豆被打的次数:{this.state.count}h1> */}
- <Counter count={this.state.count}>Counter>
- <button onClick={this.handleClick}>打豆豆button>
- div>
- )
- }
- }
-
- class Counter extends React.Component{
- render(){
- console.warn('子组件---生命周期钩子函数:render')
- return(
- <h1 id='title'>统计豆豆被打次数:{this.props.count}h1>
- )
- }
- componentDidUpdate(prevProps){
- console.warn('子组件--生命周期函数:componentDidUpdate')
- //获取DOM
- const title = document.getElementById('title')
- console.log(title.innerHTML)
- console.log('上一次的props',prevProps,',当前的props:',this.props)
-
- if(prevProps.count !== this.props.count){
- this.setState({})
- }
- }
-
-
- }
- ReactDOM.render(<App/>,//调用的是父组件
-
- document.getElementById('root'))
1.5卸载时(卸载阶段)
- class App extends React.Component{
- constructor(props){
- super(props)
- }
- state={
- count:0
- }
-
- handleClick=()=>{
- this.setState({
- count:this.state.count+1
- })
- }
-
- render(){
- return(
- <div>
- {
- this.state.count>3? <span>啊,豆豆被打死了span>
- :<Counter count={this.state.count}>Counter>
- }
-
- <button onClick={this.handleClick}>打豆豆button>
- div>
- )
- }
- }
-
- class Counter extends React.Component{
- componentDidMount(){
- setInterval(()=>{
- console.log('定时器正在进行')
- },500
- )
- }
- render(){
- return(
- <div>
- {/* {
- this.props.count>3? <span>啊,豆豆被打死了span>
- :<h1 id='title'>统计豆豆被打次数:{this.props.count}h1>
- } */}
- <h1 id='title'>统计豆豆被打次数:{this.props.count}h1>
- div>
-
- )
- }
-
- componentWillUnmount(){
- console.warn('生命周期函数:componentWillUnmount')
- //清理定时器
- clearInterval()
- }
-
- }
- ReactDOM.render(<App/>,//调用的是父组件
-
- document.getElementById('root'))
关于this.timerId可参考文章:http://t.csdn.cn/VYDQ3