Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

React Lifecycle: ภาพรวมวงจรชีวิตของ Component

3 ระยะของ React Lifecycle

  1. Mounting: Component ถูกสร้างและ Render เข้า DOM ครั้งแรก
  2. Updating: State หรือ Props เปลี่ยนแปลง Component Re-render
  3. Unmounting: Component ถูกลบออกจาก DOM

Lifecycle Methods สำคัญใน Class Component

Mounting Phase

  • constructor(props) - ตั้งค่า Initial State (Optional)
  • render() - **จำเป็น** คืนค่า JSX เพื่อ Render
  • componentWillMount() - รันก่อน Mount (Legacy, ควรใช้ constructor หรือ useEffect แทน)

Updating Phase

  • render() - เรียกใหม่เมื่อ State/Props เปลี่ยน
  • componentDidUpdate() - หลัง Update เสร็จ (Optional)

Unmounting Phase

  • componentWillUnmount() - ทำความสะอาด (Cleanup) ก่อน Unmount (Optional)

ตัวอย่าง: User Login/Logout Flow

class UserContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { currentUser: "" };
  }
  
  componentWillMount() {
    this.setState({ currentUser: "John" }); // Login
  }
  
  logout = () => {
    this.setState({ currentUser: "" }); // Logout
  }
  
  render() {
    if (this.state.currentUser === "John") {
      return (
        <UserProfile />
        <button onClick={this.logout}>Logout</button>
      );
    } else {
      return <button>Login</button>;
    }
  }
}

class UserProfile extends React.Component {
  componentWillUnmount() {
    alert("Logged Out"); // Cleanup
  }
  
  render() {
    return <h1>Welcome back, John!</h1>;
  }
}

สรุป

เข้าใจ Lifecycle ช่วยควบคุมพฤติกรรม Component ได้แม่นยำ ปัจจุบันแนะนำให้ใช้ **Hooks (useEffect)** แทน Lifecycle Methods ใน Class Component เพราะเขียนง่ายและทันสมัยกว่า