React生命周期里componentDidUpdate的基本用法

在componentDidUpdate方法中,我们通过比较前一个状态(prevState.count)和当前状态(this.state.count)的值,来判断count是否发生了变化。如果发生了变化,我们就打印出新的count值。
说白了点,就是对值进行监听。当监听值发生变化时,触发componentDidUpdate方法,对程序进行操作。

import React, {
    
     Component } from 'react';

class MyComponent extends Component {
    
    
  state = {
    
    
    count: 0,
  };

  componentDidUpdate(prevProps, prevState) {
    
    
    if (prevState.count !== this.state.count) {
    
    
      console.log('Count changed:', this.state.count);
    }
  }

  increment = () => {
    
    
    this.setState((prevState) => ({
    
     count: prevState.count + 1 }));
  };

  render() {
    
    
    return (
      <div>
        <p>Count: {
    
    this.state.count}</p>
        <button onClick={
    
    this.increment}>Increment</button>
      </div>
    );
  }
}

export default MyComponent;

在上面的示例中,我们定义了一个类组件MyComponent,其中包含一个名为componentDidUpdate的生命周期方法。在componentDidUpdate方法中,我们通过比较前一个状态(prevState.count)和当前状态(this.state.count)的值,来判断count是否发生了变化。如果发生了变化,我们就打印出新的count值。

在increment方法中,我们使用setState来更新count的值。每次点击按钮时,increment方法会被调用,从而更新count的值,并且触发组件的重新渲染。

请注意,componentDidUpdate方法接收两个参数:prevProps和prevState,分别表示前一个属性和状态的值。你可以根据具体的需求使用这些参数来执行特定的操作。

需要注意的是,在React 17及以后的版本中,官方推荐使用componentDidUpdate的替代方法,即使用useEffect钩子来监听组件更新。这是因为useEffect提供了更灵活和易于使用的方式来处理副作用操作。

猜你喜欢

转载自blog.csdn.net/z2000ky/article/details/130821255