生命周期
https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
组件的三个生命周期状态
- Mount:插入真实 DOM
- Update:被重新渲染
- Unmount:被移出真实 DOM
React 为每个状态都提供了勾子(hook)函数
- componentWillMount()
- componentDidMount()
- componentWillUpdate()
- componentDidUpdate()
- componentWillUnmount()
生命周期流程
- 第一次初始化显示
ReactDOM.render(<Xxx/>, containDom)
constructor()
componentWillMount() : 将要插入回调
render() : 用于插入虚拟DOM回调
componentDidMount() : 已经插入回调
- 每次更新 state: this.setState({})
componentWillReceiveProps(): 接收父组件新的属性
componentWillUpdate() : 将要更新回调
render() : 更新(重新渲染)
componentDidUpdate() : 已经更新回调
- 移除组件
ReactDOM.unmountComponentAtNode(containerDom)
componentWillUnmount() : 组件将要被移除回调
常用的方法
render 必须重写,返回一个自定义的虚拟DOM
constructor 初始化状态,绑定this(可以用箭头函数代替)
componentWillMount()只执行一次,已经在dom树中,适合启动/设置一些监听
componentDidMount()
componentDidUpdate() 数据更新时触发
shouldComponentUpdate(nextProps, nextState) 更新之前可以取到数据
满足条件,则渲染,否则不渲染
- shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
(比如判断操作是否过期 如果过期了 就return false)
(判读是否需要操作 如果当前操作和以前操作一样 就不修改 比如修改用户名)
可以在你确认不需要更新组件时使用。
重要的勾子
render(): 初始化渲染或更新渲染调用
componentDidMount(): 开启监听, 发送 ajax 请求
componentWillUnmount(): 做一些收尾工作, 如: 清理定时器
componentWillReceiveProps(): 接收父组件新的属性