react 生命周期

1.class组件

初次挂载
1.constructor
2.getDerivedStateFromProps
3.render
4.componentDidMount
 
更新数据
1.getDerivedStateFromProps
2.shouldComponentUpdate
3.render
4.componentDidUpdate

备注:
1.PureComponent里不能写shouldComponentUpdate
2.优化性能一般在shouldComponentUpdate

2.函数组件

函数组件并没有专门的生命周期api

useEffect将在执行 DOM 更新之后调用它
1.不传第二个参数相当于 componentDidMount 和 componentDidUpdate
2.第二个参数[],里面没有值表示只在初始化时执行一次相当于componentDidMount
3.第二个参数有值表示只有当count变化时,我们才去再次执行 useEffect.相当于watch
 
import styles from './index.less';
import { Button } from 'antd';
// import React from 'react';
import React, { useState, useEffect } from 'react';

const HomePage: React.FC = () => {
  class Cc extends React.Component {
    constructor(props: any) {
      super(props)
      console.log('constructor')
      this.state = {
        a: 1
      }
    }
    static getDerivedStateFromProps(props: any, state: any) {
      console.log('getDerivedStateFromProps')
      // console.log(props)
      // console.log(state)
      return null;
    }
    // 更新阶段
    // PureComponent里不能写shouldComponentUpdate
    // 优化生成周期
    shouldComponentUpdate() {
      console.log('shouldComponentUpdate')
      return true;
    }
    render() {
      console.log('render')
      return <div>
        <h3>class组件</h3>
        <div>初次挂载</div>
        <div>1.constructor</div>
        <div>2.getDerivedStateFromProps</div>
        <div>3.render</div>
        <div>4.componentDidMount</div>
        <Button type="primary" size="small" onClick={() => {
          console.log('修改数据')
          this.setState({
            a: 2
          })
        }}>修改数据</Button>
        <div>更新数据</div>
        <div>1.getDerivedStateFromProps</div>
        <div>2.shouldComponentUpdate</div>
        <div>3.render</div>
        <div>4.componentDidUpdate</div>
      </div>
    }
    // 组件挂载完成
    componentDidMount() {
      console.log('componentDidMount')
    }
    componentDidUpdate() {
      console.log('componentDidUpdate')
    }
  }
  const [count, setCount] = useState(0);

 
  // useEffect将在执行 DOM 更新之后调用它。
  // 1.不传第二个参数相当于 componentDidMount 和 componentDidUpdate
  // 2.第二个参数[],里面没有值表示只在初始化时执行一次相当于componentDidMount
  // 3.第二个参数有值表示只有当count变化时,我们才去再次执行 useEffect.相当于watch
  useEffect(() => {
    // 使用浏览器的 API 更新页面标题
    document.title = `You clicked ${count} times`;
  }, [count]);
  return (
    <div className={styles.container}>
      <h2>生命周期</h2>
      <h3>函数组件</h3>
      <div>函数组件并没有专门的生命周期api</div>
      <p>You clicked {count} times</p>
      <Button type="primary" size="small" onClick={() => setCount(count + 1)}>
        Click me
      </Button>
      <div>useEffect将在执行 DOM 更新之后调用它</div>
      <div>1.不传第二个参数相当于 componentDidMount 和 componentDidUpdate</div>
      <div>2.第二个参数[],里面没有值表示只在初始化时执行一次相当于componentDidMount</div>
      <div>3.第二个参数有值表示只有当count变化时,我们才去再次执行 useEffect.相当于watch</div>
      <Cc></Cc>
    </div>
  );
};



export default HomePage;

 

posted on 2024-04-08 21:39  sss大辉  阅读(4)  评论(0编辑  收藏  举报

导航