运行中(更新阶段)
表示当属性或状态发生更新时的阶段
更新阶段一共有7个钩子
componentWillReceiveProps()/UNSAFE_componentWillReceiveProps()
static getDerivedStateFromProps()
shouldComponentUpdate()
componentWillUpdate()/UNSAFE_componentWillUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
componentWillReceiveProps()/UNSAFE_componentWillReceiveProps()
当组件身上属性(props)更改时触发 ,里面有个参数,nextProps
componentWillReceiveProps( nextProps ){ console.log('更新阶段--componentWillReceiveProps') }
render () { console.log('04-render') let { changeName,name} = this.props let { count } = this.state return ( <Fragment> <h3>初始化阶段---5个钩子函数</h3> <button onClick={ changeName }>改个称呼</button> <p>称呼ta为---{ name }</p> <button onClick={ this.changeCount }>改个count</button> <p>count为:---{ count }</p> </Fragment> ) }
单击按钮改个称呼时触发了
static getDerivedStateFromProps()
和初始化阶段的那个一样
shouldComponentUpdate()
决定当props或是state更改时,组件要不要渲染, 默认返回时true
shouldComponentUpdate(){ console.log('更新阶段--shouldComponentUpdate') return true //为true渲染,false不渲染 }
componentWillUpdate()/UNSAFE_componentWillUpdate
组件即将更新
componentWillUpdate(){ console.log('更新阶段--componentwillUpdate') }
render() ---同初始化阶段的一样
getSnapshotBeforeUpdate ()
注意:这个组件不可以和componentWillMount,componentWillReceiveProps,componentWillUpdate这三个组件一起用
再这个组件不单独使用,要和componentDidUpdate一起使用
componentDidUpdate()
componentDidUpdate ( prevprops,prevstate,snapshot) { console.log(prevprops,prevstate,snapshot) console.log( '更新阶段-componentDidUpdate' ) }
销毁阶段
表示组件被卸载或者删除的阶段 ,可以进清尾工作
一个钩子
componentWillUnmount
componentWillUnmount ()
目的:销毁子组件
子组件:
componentWillUnmount(){ console.log('销毁阶段啦--componentWillUnmount') }
父组件:
constructor () { super() this.state={ name : '爸爸', flag:true } } destroy=()=>{ this.setState({ flag : false }) }
render(){ let { name,flag } = this.state return ( <div className="App"> <button onClick={ this.destroy }>销毁</button> { !flag||<Life name={ name } changeName={ this.changeName }></Life> } </div> ); }
单击销毁按钮后,子组件Life销毁,执行了子组件的钩子,打印了销毁阶段啦--componentWillUnmount
错误处理
错误处理应用于render()函数内部,指的是render内部发生错误的情况下对该情况进行对应的处理,保证程序还能够运行,而不是直接页面整个崩了
import React from 'react' class Error extends React.Component { constructor(props) { super(props); this.state = { error: false }; } componentDidCatch(error, info) { console.log('错误处理-componentDidCatch') this.setState({ error, info }); } errorHandle = () => { this.setState({ error: true }) } render() { if (this.state.error) { return ( <div> <p> 报错了 </p> { console.log(new Error("YOLO")) } </div> ) } return ( <div> <button onClick = { this.errorHandle }> 抛出错误 </button> </div> ); } } export default Error