react的生命周期方法

    xiaoxiao2025-06-22  9

    生命周期方法

    生命周期方法,指的是在组件初始化后,以及组件销毁时,会自动执行的两个方法,我们可以在初始化方法中执行获取数据的操作,在组件销毁方法中执行一些清除操作,比如清除定时器等操作。这两个方法分别是:componentDidMount 和 componentWillUnmount。

    使用示例:

    class Hello extends React.Component{ constructor(props){ super(props); this.state = {} } // 组件初始化时自动执行的方法 componentDidMount() { console.log('componentDidMount'); } // 组件销毁时自动执行的方法 componentWillUnmount(){ console.log('componentWillUnmount'); } render(){ return ( <h1>Hello world!</h1> ); } } ReactDOM.render(<Hello />,document.getElementById('root')); setTimeout(() => { ReactDOM.render(<h1>切换组件</h1>,document.getElementById('root')); }, 2000);
    最新回复(0)