Chuyển đến nội dung chính

Bài 7: ReactJS - Tìm hiểu về Component Life Cycle


Trong bài này chúng ta sẽ tìm hiểu về vòng đời của một React component và các methods để quản lý vòng đời này.

Lifecycle Methods

  • componentWillMount đây là method sẽ được thực thi trước khi 1 component được render trên cả server side và  client side.
  • componentDidMount method này được thực thi khi 1 component được render trên client side. Đây là nơi các hàm AJAX requests, DOM or update state được thực thi. Method này cũng đucợ sử dụng để kết nối với các JS Framework khác và các function với delayed execution như setTimeout or setInterval.
  • componentWillReceiveProps sẽ được thực thi ngay khi thuộc tính props (tìm hiểu props là gì?) được update và trước khi component được render lại. Trong ví dụ dưới, ta sẽ sử dung method này vùng với setNewNumber để update state.
  • shouldComponentUpdate sẽ trả về kết quả true or false. Phương thức này sẽ xác định 1 component có được update hay không. Mặc định giá trị này là true. Nếu bạn không muốn component render lại sau khi update state hay props thì return giá trị thành false. Các bạn xem ví dụ dưới để hiểu rõ.
  • componentWillUpdate được gọi khi chúng ta update state của component trước khi nó render lại.
  • componentDidUpdate sau khi componentWillUpdate ở trên được gọi xong thì đến lượt thằng này được goi.
  • componentWillUnmount được gọi khi chúng ta unmout 1 component kiểu như xóa nó khỏi react.
Chúng ta xem ví dụ dưới đây để hiểu rõ hơn về các methods ở trên. Chúng ta sẽ khởi tạo state trong App.js, hàm setNewnumber sẽ được dùng để update state và các life cycle methods nằm trong content component
App.js
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;
Trong index.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);
Kết quả render ta được:
Lúc này chỉ có 2 methods được thực thi, đó là componentWillMount và componentDidMount 
Khi chúng ta click vào button INCREMENT quá trình update state xảy ra và các life cycle methods khác sẽ được thực hiện
Nhớ hàm timeout chúng ta đã set chứ? Bây giờ sau 10s App component sẽ bị unmount và method cuối cùng được thực hiện:
Kết thúc bài 7 ở đây mọi người có thắc mắc gì thì comment bên dưới nha, mình sẽ trả lời trong vòng 24h.

Bài 8: Tạo form trong React.




Nhận xét

  1. Những bài viết của anh rất dễ hiểu, rất mong những bài viết tiếp theo. Cảm ơn anh nhiều!

    Trả lờiXóa
    Trả lời
    1. Cảm ơn sự quan tâm của bạn dành cho blog của mình :)

      Xóa
  2. Excellent article. Very interesting to read. I really love to read such a nice article. AngularJS 5 Online Course Bangalore

    Trả lờiXóa

Đăng nhận xét

Bài đăng phổ biến từ blog này

Tổng hợp danh sách các trang web lấy backlink cực tốt (P.1)

Đi backlink  trong SEO là điều mà ai cũng phải biết và đầu tư cho nó nhiều nhất. Dưới đây, mình chia sẻ các trang web có thể đi backlink khá tốt cho mọi người. Mỗi ngày các bạn tạo 1 bài post sau đó post lên 10 trang trong tổng số 40 trang này, hôm sau cũng viết 1 bài khác rồi post lên 10 trang kế, khi hết thì quay vòng lại 10 trang đầu, mình sẽ update thêm các website nên các bạn cứ yên tâm không lo hết. (Các bạn nhớ bookmark lại kẻo quên trang mình nha :) ) Nếu các bạn không rõ về DA PA IN-EXTERNAL Links thì xem ở đây:  Các chỉ số quan trọng cần biết khi làm SEO ID URL DA PA Internal Links External Links Alexa Global Rank Alexa Local Rank 1 http://diendan.zing.vn/ 63,17 54,5 168 19 701 9 2 http://vatgia.com/ 62,61 57,34 984 23 8086 71 3 http://forum.ueh.edu.vn/ 49,82 38,88 555 43 92060 774 4 http://www.5giay.vn/ 47,12 55,72 445 12 43

Viết game flappy bird bằng HTML và JavaScript (P.1)

Hôm nay chúng ta sẽ viết một game tương tự flappy bird bằng HTML và JavaScript một cách đơn giản, bài viết không chỉ giúp bạn nâng cao khả năng lập tình HTML JS mà còn tạo ra 1 sản phẩm thú vị cho nên các bạn chịu khó theo dõi nha. Các bạn xem demo sản phẩm khi chúng ta hoàn thành trên fiddle:  Demo  đây chỉ là demo cơ bản thôi, khi xem xong bài viết này các bạn có thể làm hay hơn thế nữa :)). Nào ta bắt đầu thôi. HTML Canvas Đầu tiên để tạo game chúng ta cần tạo background cho nó, chúng ta sẽ dùng HTML Canvas , Canvas là một element tuyệt vời cho việc thiết kế game trong HTML. Chúng ta sẽ dùng Js để vẽ trên Canvas. Nếu các bạn chưa biết về Canvas mình có để link phía dưới để các bạn tìm hiểu nên hiện giờ cứ yên tâm mà xem tiếp nha. Bây giờ các bạn tạo 1 file html và nhập đoạn code sau: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <style> canvas {

Xdebug, PhpStorm and Docker - Why it not working?

  Lately, i start new job with Magento, and while setup IDE for project i face problem with Xdebug, PhpStorm and Docker. It took me a lot of hours to find out and make it work. So i write this post to save some step for you guys also me some way to solve the stuck when we got. 1. How Xdebug work: Link  i founded this article with quite easy understand explanation how xdebug work, so spend some minutes to read it, we need to understans the thing we do to easy to solve it. 2: Define Xdebug is installed on server: With php -v you should see Xdebug showed. And with phpinfo() If you dont see it showed, it mean you have not installed it or it not enable Checking if you have enable extension from your php ini. Or if you have not installed it, consider its document: Link . 3. Now if you make sure xdebug installed but your break point at PhpStorm not break, continue these steps: In phpinfo(), make sure  xdebug.remote_enable is On cause you are using docker container, also checking  xdebug.remot