Sobes.tech
Junior — Middle

Kokius etapus pereina React komponentai nuo jų sukūrimo iki pašalinimo iš DOM?

sobes.tech AI

Atsakymas iš AI

React komponentai pereina per keletą pagrindinių gyvenimo ciklo etapų, nuo sukūrimo iki pašalinimo iš DOM:

  1. Montavimas (Mounting) — komponento sukūrimas ir įterpimas į DOM.

    • Constructor
    • static getDerivedStateFromProps
    • render
    • componentDidMount
  2. Atnaujinimas (Updating) — įvyksta keičiant props arba state.

    • static getDerivedStateFromProps
    • shouldComponentUpdate
    • render
    • getSnapshotBeforeUpdate
    • componentDidUpdate
  3. Nuėmimas (Unmounting) — komponento pašalinimas iš DOM.

    • componentWillUnmount
  4. Klaidų tvarkymas (Error Handling) — įvykus klaidoms vaikų komponentuose.

    • static getDerivedStateFromError
    • componentDidCatch

Pavyzdys, kaip naudoti gyvenimo ciklo metodus klasės komponentuose:

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

  componentDidMount() {
    console.log('Komponentas įmontuotas');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('Komponentas atnaujintas');
  }

  componentWillUnmount() {
    console.log('Komponentas bus pašalintas');
  }

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

Funkcinėse komponentuose, naudojant hook'us, panašūs etapai įgyvendinami per useEffect ir kitus hook'us.