+1

Làm quen với React.Component

**Giới thiệu **

React.Component là một lớp cơ sở trừu tượng, vì vậy nó hiếm khi được sử dụng trực tiếp. Thay vào đó, bạn thường phân lớp nó, và định nghĩa ít nhất một phương thức render ().Thông thường bạn sẽ định nghĩa 1 React.Component thông qua 1 class của Javascript

class Greeting extends React.Component {
    render() {
      return <h1>Hello, {this.props.name}</h1>;
    }
}

Mỗi component có một số "lifecycle method" mà bạn có thể ghi đè để chạy mã tại những thời điểm cụ thể trong tiến trình. Methods đươc gắn với tiền tố "will" được gọi trước khi có sự kiện gì đó xảy ra , và methods gắn với tiền tố "did" sẽ được gọi ngay sau 1 sự kiện diễn ra .Bài viết này sẽ giới thiệu 1 vài "lifecycle method" như:

Mounting: Các phương thức này được gọi khi một cá thể của một component đang được tạo và chèn vào DOM:

  • constructor()
  • componentWillMount()
  • render()
  • componentDidMount()

Updating Cập nhật có thể là do thay đổi props hoặc state. Các phương pháp này được gọi khi một component đang được render lại:

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • componentDidUpdate()

Unmounting những method được gọi khi 1component bị xoá khỏi DOM:

  • componentWillUnmount()

Ta sẽ đi sâu vào tìm hiểu về các method đã liệt kê ở trên.

  1. Render hàm render() là 1 method bắt buộc phải có trong mỗi class của React. Khi được gọi, nó sẽ kiểm tra các đối tượng this.props và this.state và trả về một element của React. Phần tử này có thể là một đại diện của một thành phần DOM gốc, chẳng hạn như

    , hoặc thành phần phức hợp khác mà bạn tự định nghĩa.

  2. Contructor Contructor cho một thành phần React được gọi trước khi được gắn kết. Khi triển khai constructor cho một lớp con React.Component, bạn nên gọi super (props) trước bất kỳ câu lệnh nào khác. Nếu không, this.props sẽ bị undefined trong constructor, có thể dẫn đến lỗi.

    constructor(props) {
      super(props);
      this.state = {
        color: props.initialColor
      };
    }
    
  3. componentWillMount ComponentWillMount() Được thực hiện trước khi render(), trên cả sercer và phía client.

  4. componentDidMount ComponentDidMount() được gọi ngay sau khi một component được gắn sự kiện kết. Nếu muốn thực hiện khởi tạo yêu cầu các nút DOM nên khai báo vào đây. Nếu bạn cần tải dữ liệu từ một remote hoặc 1 API, đây là một nơi tốt để nhanh chóng yêu cầu đó. Thiết lập trạng thái trong phương thức này sẽ kích hoạt việc render lại View.

  5. componentWillReceiveProps()

    componentWillReceiveProps(nextProps)
    

    componentWillReceiveProps() được gọi trước khi một component nhận 1 props mới. Nếu bạn muộn cập nhât state trong 1 response để thay đổi 1 prop, bạn sẽ cần thực hiện việc so sánh sự thay đổi giữa các attributes :this.props , nextProps va thực hiện việc thay đổi thông qua hàm this.setState().

  6. shouldComponentUpdate() shouldComponentUpdate() trả về giá trị boolean ,thực hiện việc kiểm chứng xem 1 compnent thực sự là có sự thay đổi hay ko.Giá trị mặc định của hàm này luôn luôn trả về là true. Nếu bạn muốn 1 component ko đc show lên VIew khi mà prop hoặc state có sự thay đổi, bạn có thể set shouldComponentUpdate() là false để thực hiện việc đó.

Vị dụ về sự hoạt động của các hàm đã nêu ở trên:

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;
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);

https://facebook.github.io/react/docs/react-component.html https://www.tutorialspoint.com/reactjs/reactjs_component_life_cycle.htm


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí