Hooks in React — บทนำ

Jan 21 2023
Hooks ถูกเพิ่มเข้ามาใน React ในเวอร์ชัน 16.8 และทำให้สามารถใช้สถานะในส่วนประกอบการทำงานของ React ได้
โลโก้ตอบสนอง

Hooks ถูกเพิ่มเข้ามาใน React ในเวอร์ชัน 16.8 และทำให้สามารถใช้สถานะในส่วนประกอบการทำงานของ React ได้ ก่อนหน้านี้ส่วนประกอบของคลาสเท่านั้นที่สามารถเข้าถึงสถานะได้ การเพิ่มตะขอใหม่นี้ทำให้ง่ายต่อการจัดการกับสถานะในปฏิกิริยา

//handling state in React class component
import React from "react"

class App extends React.Component {

  constructor(props) {    
    super(props);    
    this.state = {name: "Thushitha"};  
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <p>I'm {this.state.name}</p>      
      </div>
    );
  }
}

export default App;

import {useState} from 'react'

  1. สามารถใช้ได้เฉพาะในองค์ประกอบการทำงานของ React เท่านั้น
  2. สามารถเรียกใช้ได้ที่ด้านบนของส่วนประกอบเท่านั้น
  3. //importing required hook from react
    import {useState} from 'react'
    
    export default function App() {
    
      // correctly calling useState hook
      const [name,setName]=useState("Max")
    
      if(name==="Max"){
        //wrong usage as this hook is called conditionally. The hooks have to be 
        //called in the same order in every rendering
        const [school,setSchool]=useState("ABC School");
      }else{
        const [college,setCollege]=useState("XYZ College");
      }
    
      return (
        <div>
          <h1>Hello World!</h1>
        </div>
      );
    }