Haki w React — Wprowadzenie

Jan 21 2023
Hooki zostały dodane do Reacta w wersji 16.8 i umożliwiły wykorzystanie stanu w komponentach funkcjonalnych Reacta.
Reaguj logo

Hooki zostały dodane do Reacta w wersji 16.8 i umożliwiły wykorzystanie stanu w komponentach funkcjonalnych Reacta. Wcześniej tylko komponenty klasy miały dostęp do stanu. Ten nowy dodatek haków ułatwił radzenie sobie ze stanem w reakcji.

//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. Można ich używać tylko w komponentach funkcjonalnych React
  2. Można je wywołać tylko na górze komponentów.
  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>
      );
    }