React知识摘要

react新的生命周期

2019-12-14  本文已影响0人  郭海杰

react-dom.development.js:12357 Warning: componentWillMount has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.

import React, { Component } from 'react'
class Second extends Component {
    constructor(props) {
        super(props)
        console.log("初始化state")
        this.state = {
            num: 1,
            list: [1, 2, 3]
        }
    }

    static getDerivedStateFromProps(props, state) {

        console.log("组件初始化:getDerivedStateFromProps:" + props)
        console.log(state)
        console.log(props)
        //组件每次被rerender的时候,包括在组件构建之后(虚拟dom之后,实际dom挂载之前),每次获取新的props或state之后;
        //每次接收新的props之后都会返回一个对象作为新的state,返回null则说明不需要更新state
        return state
    }
    componentDidCatch(error, info) { // 获取到javascript错误

    }
    render() {
        return (
            <>
                {console.log("开始渲染dom")}

                <div>
                    <ul>
                        {
                            this.state.list.map((item, index) => {
                                return (
                                    <li key={index + item}>{item}</li>
                                )
                            })
                        }
                    </ul>
                </div>
                <div>
                    <button onClick={this.subtraction.bind(this)}>-</button>
                    <span>{this.state.num}</span>
                    <button onClick={this.addition.bind(this)}>+</button>
                </div>
                {console.log("渲染完毕")}

            </>
        );
    }
    addition() {
        let num = this.state.num + 1
        this.setState({
            num: num
        })
    }
    subtraction() {
        console.log(this.state.num)
        let num = this.state.num - 1
        this.setState({
            num: num
        })
    }

    // UNSAFE_componentWillMount() {
    //     console.log("初始化数据,渲染前:componentWillMount")

    // }

    componentDidMount() {
        console.log("DOM挂载后,已经渲染了:componentDidMount")

    }
    // UNSAFE_componentWillReceiveProps(newProps) {
    //     console.log("组件收到新的props:componentWillReceiveProps:" + newProps)

    // }
    shouldComponentUpdate(newProps, newState) {
        console.log("组件发生了更新,组件是否更新:shouldComponentUpdate:" + newState)
        return true;
    }
    // UNSAFE_componentWillUpdate(nextProps, nextState) {
    //     console.log("组件开始更新:componentWillUpdate")
    // }
    getSnapshotBeforeUpdate(prevProps, prevState) { // 组件更新前触发
        console.log("组件更新前:getSnapshotBeforeUpdate")
    }
    componentDidUpdate(prevProps, prevState) {
        console.log("组件完成更新:componentDidUpdate")

    }
    componentWillUnmount() {
        console.log("组件被卸载:componentWillUnmount")
    }

}

export default Second
上一篇下一篇

猜你喜欢

热点阅读