## :-: 组件生命周期 [State & 生命周期](https://react.docschina.org/docs/state-and-lifecycle.html) ``` import React from "react"; class LifeCyle extends React.Component { static defaultProps = {}; static propTypes = {}; constructor() { console.log(1, "constructor"); super(); this.state = {}; } // // 将要被挂载 // componentWillMount() { // // 官方不建议这里进行ajax 16.3版本后移除了componentWillMount // console.log(2, "componentWillMount"); // } // 16.3版本新增加 static getDerivedStateFromProps() { // 第一次挂载也会执行 // 必须有返回值 return null; } // 开始渲染 render() { // 不要调用this.setState、函数会被重复多次执行(死循环) console.log(3, "render"); return <div>123</div>; } // 已经被挂载 componentDidMount() { // 在这里就可以愉快的调用ajax请求了、、 // ajax this.setState console.log(4, "componentDidMount"); } // // props 数据被改变时执行 // componentWillReceiveProps() { // // 第一次挂载不执行,之后执行 // // 官方不建议这里进行ajax 16.3版本后移除了componentWillReceiveProps // console.log(8, "componentWillReceiveProps"); // } // 数据将要被更改时执行 shouldComponentUpdate(nextProps, nextState) { // nextProps -- 将要被改变的值 // nextState -- 将要被改变的状态 // 优化性能 console.log(5, "componentDidMount"); // 返回 true更新视图、false不更新视图 return false; } // 16.3版本新增加 // getSnapshotBeforeUpdate 跟 componentDidUpdate 是成对出现的、 getSnapshotBeforeUpdate() { // 必须有返回值 return null; } // // 将要更新视图 // componentWillUpdate() { // // 16.3版本后移除了componentWillUpdate // // 不能设置状态(死循环) // console.log(6, "componentWillUpdate"); // } // 更新完毕 componentDidUpdate() { // 不能设置状态(死循环) console.log(7, "componentDidUpdate"); } // 组件将要被卸载、移除 componentWillUnmount() { console.log(9, "componentWillUnmount"); } } export default LifeCyle; ```