react 生命周期(新)

126 阅读1分钟

react 生命周期(新)

    <script type="text/babel">
        class Demo extends React.Component{
            state = {newArr:[]};
            componentDidMount(){
                setInterval(() => {
                    // 获取原状态
                    const {newArr} = this.state;
                    // 模拟一条新闻
                    const news = '新闻'+(newArr.length+1)
                    // 更新状态
                    this.setState({newArr:[news,...newArr]})
                }, 1000);
            }
            getSnapshotBeforeUpdate(){
                // 将当前的长度返回给componentDidUpdate中的height
                return this.refs.list.scrollHeight
            }
            componentDidUpdate(preProps,preState,height) {
                this.refs.list.scrollTop+= this.refs.list.scrollHeight-height
            }
            render(){
                return(
                    <div className="list" ref="list"> 
                        {
                            this.state.newArr.map((n,index)=>{
                                return <div key={index} className="new">{n}</div>
                            })
                        }
                    </div>

                )
            }
        }
        ReactDOM.render(<Demo/>,document.querySelector('.test'))
    </script>

总结

新旧版本的去别:去掉3个旧的(componentWillMount ,componentWillReceiveProps,componentWillUpdate),增加2个新的(getDerivedStateFromProps,getSnapshotBeforeUpdate)

初始化阶段:由ReactDOM.render()触发 ---初次渲染

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

更新阶段:由组件内部this.setState()或父组件render触发

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render() ===>必须使用的一个
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

卸载组件:由ReactDOM.unmountComponentAtNode()触发

  1. componentWillUnmount()

重要的钩子

  1. render:初始化渲染或更新渲染调用
  2. componentDidMount:开启监听,发送Ajax请求
  3. componentWillUnmount:做一些收尾的工作,例:清除定时器

即将废弃的钩子

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

现在使用会出现一些警告,16版本需要UNSAFE_前缀才能使用