【第27期】一文了解React生命周期
概述
React生命周期是指在组件的不同阶段,React会自动调用的一系列方法。它们可以用于控制组件的行为、处理副作用、更新状态等。
React生命周期
在React中,组件的生命周期可以分为三个阶段:挂载(Mounting)、更新(Updating)和卸载(Unmounting)。每个阶段都对应着不同的生命周期方法。
挂载阶段(Mounting)
-  
     
constructor:组件被创建时调用,用于初始化状态和绑定方法。  -  
     
static getDerivedStateFromProps:在组件实例化和更新时调用,用于根据props的变化来更新状态。  -  
     
render:根据props和state渲染组件的内容。  -  
     
componentDidMount:组件挂载后调用,可以进行异步操作、订阅事件等。  
以下是React中挂载的一些案例:
挂载阶段(Mounting):
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  componentDidMount() {
    console.log('Component mounted');
  }
  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
 
   在上述例子中,组件首次挂载时,会打印出"Component mounted"。点击按钮时,会更新组件的状态,重新渲染。
更新阶段(Updating)
-  
     
static getDerivedStateFromProps:在组件更新时调用,用于根据props的变化来更新状态。  -  
     
shouldComponentUpdate:决定组件是否需要重新渲染,默认返回true。  -  
     
render:根据props和state渲染组件的内容。  -  
     
getSnapshotBeforeUpdate:在组件更新前获取DOM的快照,返回值将作为第三个参数传递给componentDidUpdate。  -  
     
componentDidUpdate:组件更新后调用,可以进行DOM操作、网络请求等。  
以下是React中更新的一些案例:
更新阶段(Updating):
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  componentDidUpdate() {
    console.log('Component updated');
  }
  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
 
   在上述例子中,每次更新组件时,都会打印出"Component updated"。
卸载阶段(Unmounting):
-  
     
componentWillUnmount:组件卸载前调用,可以进行清理操作,如取消订阅、清除定时器等。  
除了上述的生命周期方法,React还提供了一些特殊的方法,如错误处理相关的方法:
-  
     
static getDerivedStateFromError:在子组件发生错误时调用,用于更新错误状态。  -  
     
componentDidCatch:在子组件发生错误后调用,可以记录错误信息、发送错误报告等。  
需要注意的是,React 16.3版本以后,一些生命周期方法被标记为过时(deprecated),不再推荐使用。而且,React Hooks的引入也改变了组件的生命周期概念,可以使用useEffect等Hooks来替代生命周期方法的功能。以下是React中卸载的一些案例:
卸载阶段(Unmounting):
class App extends React.Component {
  componentDidMount() {
    this.timer = setInterval(() => {
      console.log('Timer tick');
    }, 1000);
  }
  componentWillUnmount() {
    clearInterval(this.timer);
    console.log('Component unmounted');
  }
  render() {
    return <h1>Hello, World!</h1>;
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
setTimeout(() => {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
}, 5000);
 
   在上述例子中,组件挂载后,会每秒打印一次"Timer tick"。5秒后,组件被卸载,会打印出"Component unmounted",同时定时器也被清除。
React与Vue生命周期对比
React和Vue是两个非常流行的JavaScript框架,它们都提供了生命周期方法来管理组件的行为。下面是React和Vue生命周期的对比:
React生命周期方法:
-  
     
挂载阶段:constructor、static getDerivedStateFromProps、render、componentDidMount  -  
     
更新阶段:static getDerivedStateFromProps、shouldComponentUpdate、render、getSnapshotBeforeUpdate、componentDidUpdate  -  
     
卸载阶段:componentWillUnmount  
Vue生命周期方法:
-  
     
创建阶段:beforeCreate、created、beforeMount、mounted  -  
     
更新阶段:beforeUpdate、updated  -  
     
销毁阶段:beforeDestroy、destroyed  
React和Vue生命周期方法的名称和执行顺序有一些差异,但它们的作用和用途是类似的。
-  
     
React的生命周期方法更加细分和灵活,可以通过shouldComponentUpdate方法来控制组件的重新渲染,而且React Hooks的引入也提供了更灵活的方式来处理组件的状态和副作用。
 -  
     
Vue的生命周期方法在创建、更新和销毁阶段都有对应的方法,使得开发者可以更方便地处理组件的行为。Vue还提供了beforeCreate和created方法来进行组件的初始化操作,而React的constructor方法则用于初始化组件的状态和绑定方法。
 
总的来说,React和Vue的生命周期方法在概念和功能上是相似的,但具体的方法名称和执行顺序有所差异。开发者可以根据自己的需求选择适合的框架和生命周期方法来管理组件的行为。
