各阶段钩子的执行顺序
constructor:初始化
- 如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
在 React 组件挂载之前,会调用它的构造函数。在为 React.Component 子类实现构造函数时,应在其他语句之前前调用
super(props)。否则,this.props在构造函数中可能会出现未定义的 bug。class App extends React.Component {constructor(props){ // 创建时,挂载之前super(props)}}
shouldComponentUpdate:是否更新 UI
state 地址改变,但是数据内容不变时不进行更新
class App extends React.Component {constructor(props) {super(props);this.state = {n: 0};}add = () => { // 先加1再减1,结果不变,改变地址this.setState( (state)=> ({n: state.n + 1}) )this.setState( (state)=> ({n: state.n - 1}) )}shouldComponentUpdate(nextProps, nextState){return !( this.state.n === nextState.n ) // 对比新旧 state.n// 等同于 this.state.n === nextState.n ? false : true}render() {return (<h1> n:{this.state.n}<button onClick={ this.add }>+1</button> // button.onClick.call(null,event)</h1>)}}
class App extends React.PureConponent对比新旧 state、props 的所有 key 的值class Hello extends React.PureComponent {constructor(props) {super(props);this.state = {n: 0};}add = () => { // 先加1再减1,结果不变,改变地址this.setState( (state)=> ({n: state.n + 1}) )this.setState( (state)=> ({n: state.n - 1}) )}render() {return (<h1> n:{this.state.n}<button onClick={ this.add }>+1</button> // button.onClick.call(null,event)</h1>)}}
render:创建虚拟 DOM
class 组件中唯一必须实现的方法
只能有一个根元素,如果有多个需要用
<React.Fragment></React.Fragment>包裹,简写<></>class Hello extends React.Component {render() {return (<><div>xxx</div><div>yyy</div></>)}}
componentDidMount:挂载到页面
首次渲染执行
- 挂载之后才可以获取 dom
官方推荐此时发起加载数据的 AJAX 请求
class App extends React.Component {constructor(props) {super(props)const div = document.getElementById('xxx')console.log(div) // null}componentDidMount() {const div = document.getElementById('xxx')console.log(div) // <div id="xxx">你好</div>}render() {return (<div id='xxx'>你好</div>)}}
ref
class App extends React.Component {constructor(props) {super(props)this.divRef = React.createRef()}componentDidMount() {const div = this.divRef.currentconsole.log(div) // <div id="xxx">你好</div>}render() {return (<div ref={ this.divRef }>你好</div>)}}
componentDidUpdate(prevProps,prevState):组件更新
首次渲染不会执行
- 此时 setState 会无限循环,除非放在 if 语句里
如果
shouldComponentUpdate返回 false,则不会触发此钩子componentWillUnmount():组件即将消亡
元素即将消亡时执行
- 此时应对长期有效的监听、计时器或 AJAX 进行取消
componentWillReceiveProps:poops变化时 - 弃用
UNSAFE_componentWillReceiveProps
