ReactJs 专题
您的位置:JS框架 > ReactJs专题 > ReactJS组件生命周期
ReactJS组件生命周期
作者:--    发布时间:2019-11-20

在本章中,我们来了解组件生命周期方法。

生命周期方法

  • componentwillmount - 在渲染之前在服务器端和客户端执行。
  • componentdidmount - 仅在客户端的第一次渲染之后执行。 这是ajax请求和dom或状态更新应该发生的地方。此方法也用于与其他javascript框架以及任何延迟执行的函数(如settimeoutsetinterval)进行集成,在这里使用它来更新状态,以便我们可以触发其他生命周期方法。
  • componentwillreceiveprops - 只要在另一个渲染被调用之前更新props就被调用。 当我们更新状态时,从setnewnumber触发它。
  • shouldcomponentupdate - 应该返回truefalse值。 这将决定组件是否将被更新。 默认设置为true。 如果确定组件在stateprops更新后不需要渲染,则可以返回false值。
  • componentwillupdate - 在渲染之前被调用。
  • componentdidupdate - 在渲染之后被调用。
  • componentwillunmount - 在从dom卸载组件后被调用,也就是卸载main.js中的组件。

在下面的例子中,将在构造函数中设置初始状态。 setnewnumber用于更新状态。 所有生命周期方法都在内容组件中。

文件:app.jsx -

import react from 'react';

class app extends react.component {
   constructor(props) {
      super(props);

      this.state = {
         data: 0
      }
      this.setnewnumber = this.setnewnumber.bind(this)
   };
   setnewnumber() {
      this.setstate({data: this.state.data + 1})
   }
   render() {
      return (
         <div>
            <button onclick = {this.setnewnumber}>increment</button>
            <content mynumber = {this.state.data}></content>
         </div>
      );
   }
}
class content extends react.component {
   componentwillmount() {
      console.log('component will mount!')
   }
   componentdidmount() {
      console.log('component did mount!')
   }
   componentwillreceiveprops(newprops) {    
      console.log('component will recieve props!')
   }
   shouldcomponentupdate(newprops, newstate) {
      return true;
   }
   componentwillupdate(nextprops, nextstate) {
      console.log('component will update!');
   }
   componentdidupdate(prevprops, prevstate) {
      console.log('component did update!')
   }
   componentwillunmount() {
      console.log('component will unmount!')
   }
   render() {
      return (
         <div>
            <h3>{this.props.mynumber}</h3>
         </div>
      );
   }
}
export default app;

文件:main.js -

import react from 'react';
import reactdom from 'react-dom';
import app from './app.jsx';

reactdom.render(<app/>, document.getelementbyid('app'));

settimeout(() => {
   reactdom.unmountcomponentatnode(document.getelementbyid('app'));}, 10000);

初始渲染之后,应该会得到如下演示效果 -

只有componentwillmountcomponentdidmount将被记录在控制台中,因为还没有更新任何东西。

当点击increment按钮时,将发生更新,并触发其他生命周期方法。

十秒钟后,组件将被卸载,最后一个事件将被记录在控制台中。

注 - 生命周期方法将始终以相同的顺序调用,因此按照示例中所示的正确顺序编写生命周期方法是一种很好的做法。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册