Khóa học react-native

Vòng Đời Trong React Native

0 phút đọc

Vòng đời của một component trong React Native là một khái niệm quan trọng mà mọi lập trình viên cần hiểu rõ để xây dựng các ứng dụng di động hiệu quả và tối ưu. Vòng đời của một component bao gồm các giai đoạn từ khi component được tạo ra, cập nhật, và cuối cùng là bị hủy. Trong bài viết này, chúng ta sẽ tìm hiểu chi tiết về các giai đoạn này, các phương thức vòng đời liên quan, và cách sử dụng chúng trong React Native.

Giới Thiệu Về Vòng Đời Component

Mỗi component trong React Native có một vòng đời mà bạn có thể theo dõi và thao tác trong ba giai đoạn chính: Mounting, Updating, và Unmounting. Mỗi giai đoạn có một tập hợp các phương thức vòng đời được gọi tại các thời điểm cụ thể, cho phép bạn kiểm soát hành vi của component và thực hiện các hành động cụ thể.

Các Giai Đoạn Chính

  1. Mounting: Giai đoạn khi một component được tạo ra và chèn vào DOM.
  2. Updating: Giai đoạn khi một component được cập nhật do thay đổi state hoặc props.
  3. Unmounting: Giai đoạn khi một component bị loại bỏ khỏi DOM.

Giai Đoạn Mounting

Giai đoạn Mounting là khi một instance của component được tạo ra và chèn vào DOM. Các phương thức vòng đời trong giai đoạn này bao gồm:

  1. constructor()
  2. static getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

constructor()

Phương thức constructor() được gọi đầu tiên khi component được khởi tạo. Nó thường được sử dụng để khởi tạo state và bind các phương thức.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
    this.increment = this.increment.bind(this);
  }

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <View>
        <Text>{this.state.count}</Text>
        <Button title="Increment" onPress={this.increment} />
      </View>
    );
  }
}

static getDerivedStateFromProps()

Phương thức getDerivedStateFromProps() được gọi ngay trước khi render, cả khi mount và update. Nó cho phép bạn cập nhật state dựa trên props mới.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      derivedValue: props.initialValue,
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.initialValue !== prevState.derivedValue) {
      return {
        derivedValue: nextProps.initialValue,
      };
    }
    return null;
  }

  render() {
    return (
      <View>
        <Text>{this.state.derivedValue}</Text>
      </View>
    );
  }
}

render()

Phương thức render() là phương thức duy nhất bắt buộc trong một component. Nó trả về các phần tử React để hiển thị trên màn hình.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class MyComponent extends Component {
  render() {
    return (
      <View>
        <Text>Hello, World!</Text>
      </View>
    );
  }
}

componentDidMount()

Phương thức componentDidMount() được gọi ngay sau khi component được render lần đầu tiên. Đây là nơi thích hợp để thực hiện các yêu cầu mạng hoặc thiết lập các subscription.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class MyComponent extends Component {
  componentDidMount() {
    // Thực hiện yêu cầu mạng hoặc thiết lập subscription
    console.log("Component did mount");
  }

  render() {
    return (
      <View>
        <Text>Component Mounted</Text>
      </View>
    );
  }
}

Giai Đoạn Updating

Giai đoạn Updating xảy ra khi component nhận props mới hoặc state thay đổi. Các phương thức vòng đời trong giai đoạn này bao gồm:

  1. static getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

shouldComponentUpdate()

Phương thức shouldComponentUpdate() được gọi trước khi render khi nhận props hoặc state mới. Nó cho phép bạn kiểm soát việc component có nên re-render hay không.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    // Chỉ re-render nếu count thay đổi
    return nextState.count !== this.state.count;
  }

  render() {
    return (
      <View>
        <Text>{this.state.count}</Text>
      </View>
    );
  }
}

getSnapshotBeforeUpdate()

Phương thức getSnapshotBeforeUpdate() được gọi ngay trước khi các thay đổi từ VDOM được phản ánh vào DOM. Nó cho phép bạn chụp lại một số thông tin từ DOM trước khi nó thay đổi.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class MyComponent extends Component {
  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Chụp lại vị trí cuộn trước khi cập nhật
    return { scrollPosition: window.scrollY };
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (snapshot) {
      // Sử dụng thông tin snapshot
      console.log("Scroll position before update:", snapshot.scrollPosition);
    }
  }

  render() {
    return (
      <View>
        <Text>Component Updated</Text>
      </View>
    );
  }
}

componentDidUpdate()

Phương thức componentDidUpdate() được gọi ngay sau khi component được cập nhật. Đây là nơi thích hợp để thực hiện các yêu cầu mạng dựa trên props mới hoặc cập nhật DOM.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class MyComponent extends Component {
  componentDidUpdate(prevProps, prevState) {
    if (this.props.data !== prevProps.data) {
      // Thực hiện yêu cầu mạng hoặc cập nhật DOM
      console.log("Component did update");
    }
  }

  render() {
    return (
      <View>
        <Text>Component Updated</Text>
      </View>
    );
  }
}

Giai Đoạn Unmounting

Giai đoạn Unmounting xảy ra khi component bị loại bỏ khỏi DOM. Phương thức vòng đời trong giai đoạn này bao gồm:

  1. componentWillUnmount()

componentWillUnmount()

Phương thức componentWillUnmount() được gọi ngay trước khi component bị loại bỏ khỏi DOM. Đây là nơi thích hợp để dọn dẹp các subscription, hủy bỏ các yêu cầu mạng, hoặc xóa các bộ đếm thời gian.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class MyComponent extends Component {
  componentWillUnmount() {
    // Dọn dẹp các subscription hoặc hủy bỏ các yêu cầu mạng
    console.log("Component will unmount");
  }

  render() {
    return (
      <View>
        <Text>Component Will Unmount</Text>
      </View>
    );
  }
}

Giai Đoạn Xử Lý Lỗi

Giai đoạn xử lý lỗi xảy ra khi có lỗi trong quá trình render, trong một phương thức vòng đời, hoặc trong constructor của bất kỳ component con nào. Các phương thức vòng đời trong giai đoạn này bao gồm:

  1. static getDerivedStateFromError()
  2. componentDidCatch()

static getDerivedStateFromError()

Phương thức getDerivedStateFromError() được gọi khi có lỗi xảy ra trong quá trình render. Nó cho phép bạn cập nhật state để hiển thị giao diện dự phòng.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return (
        <View>
          <Text>Something went wrong.</Text>
        </View>
      );
    }

    return this.props.children;
  }
}

componentDidCatch()

Phương thức componentDidCatch() được gọi khi có lỗi xảy ra trong quá trình render. Nó cho phép bạn ghi lại thông tin lỗi.

Ví dụ:

import React, { Component } from "react";
import { View, Text } from "react-native";

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // Ghi lại thông tin lỗi
    console.log("Error:", error);
    console.log("Error Info:", info);
  }

  render() {
    if (this.state.hasError) {
      return (
        <View>
          <Text>Something went wrong.</Text>
        </View>
      );
    }

    return this.props.children;
  }
}

Kết Luận

Hiểu rõ về vòng đời của component trong React Native là một phần quan trọng để xây dựng các ứng dụng di động hiệu quả và tối ưu. Bằng cách sử dụng các phương thức vòng đời một cách hợp lý, bạn có thể kiểm soát hành vi của component và thực hiện các hành động cụ thể tại các thời điểm khác nhau trong vòng đời của nó. Hy vọng qua bài viết này, bạn đã có thể nắm bắt được cách sử dụng các phương thức vòng đời trong React Native và áp dụng vào các dự án của mình.

Avatar
Được viết bởi

TechMely Team

Gợi ý câu hỏi phỏng vấn

Gợi ý bài viết

Bình luận

Chưa có bình luận nào

Khoá học javascript từ cơ bản đến chuyên sâuYoutube Techmely