深入了解 React 组件的生命周期

在 React 中,每当我们创建一个新的组件时,都会经历一系列的步骤,这被称为生命周期。React 为我们提供了一系列生命周期方法,可以让我们跟踪这些步骤并添加相应的逻辑。
下面是常见的生命周期方法:

  • constructor()
  • componentDidMount()
  • componentWillUnmount()
  • componentDidUpdate()
  • shouldComponentUpdate()
  • componentDidCatch()
  • getDerivedStateFromProps()
  • getSnapshotBeforeUpdate()
  • render()
    constructor():在组件第一次被加载的时候调用,在此期间可以初始化状态、绑定事件等。
class MyComponent extends React.Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
    
      name: 'John'
    };
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick() {
    
    }
  
  render() {
    
    }
}

componentDidMount():组件在首次渲染完成后调用,可以在这里发起 AJAX 请求或者添加事件监听器。

class MyComponent extends React.Component {
    
    
  componentDidMount() {
    
    
    fetch('/api/data')
      .then(response => response.json())
      .then(data => this.setState({
    
    data}));
  }
  
  render() {
    
    }
}

componentWillUnmount():组件即将从 dom 中移除时调用,可以在此时清除定时器或者取消网络请求。

class MyComponent extends React.Component {
    
    
  componentWillUnmount() {
    
    
    clearTimeout(this.timeoutId);
  }
  
  render() {
    
    }
}

componentDidUpdate(prevProps, prevState):组件重新-render之后调用,在这里可以检查 props 和 state 是否发生改变,从而作出反应。

class MyComponent extends React.Component {
    
    
  componentDidUpdate(prevProps, prevState) {
    
    
    if (prevProps.data !== this.props.data || prevState.name !== this.state.name) {
    
    
      console.log('数据或状态发生了改变!');
    }
  }
  
  render() {
    
    }
}

shouldComponentUpdate(nextProps, nextState): 返回一个布尔值,如果 true,则会进行重新渲染,否则跳过渲染。

class MyComponent extends React.Component {
    
    
  shouldComponentUpdate(nextProps, nextState) {
    
    
    return nextProps.data !== this.props.data || nextState.name !== this.state.name;
  }
  
  render() {
    
    }
}

getDerivedStateFromProps(nextProps, nextState):在每次渲染之前被调用,可以在这里计算新状态并返回一个新的对象。

class MyComponent extends React.Component {
    
    
  static getDerivedStateFromProps(nextProps, nextState) {
    
    
    const newState = {
    
    };
    if (nextProps.data !== this.props.data) {
    
    
      newState.data = nextProps.data;
    }
    
    return newState;
  }
  
  render() {
    
    }
}

getSnapshotBeforeUpdate(prevProps, prevState):在 componentDidUpdate 之前调用,可以在此时返回一个值,然后在 componentDidUpdate 中使用这个值。

class MyComponent extends React.Component {
    
    
  getSnapshotBeforeUpdate(prevProps, prevState) {
    
    
    return prevProps.data !== this.props.data;
  }
  
  componentDidUpdate(prevProps, prevState, snapshot) {
    
    
    if (snapshot) {
    
    
      console.log('数据已经改变了!');
    }
  }
  
  render() {
    
    }
}

render(): 组件的主要职责,返回的是一个 JSX 元素。
React 生命周期是一个非常重要的话题,熟练掌握生命周期方法可以更好地管理和优化组件的状态和行为。以上就是在 React 中使用生命周期的一些基本概念和使用方法,请多多实践!

猜你喜欢

转载自blog.csdn.net/weixin_46002631/article/details/134317334