Junior — Middle
Kādas posmos pārdzīvo React komponenti no to izveides līdz to izņemšanai no DOM?
sobes.tech AI
Atbilde no AI
React komponenti pāriet caur vairākām galvenajām dzīves cikla posmām, sākot no izveides līdz izņemšanai no DOM:
-
Montēšana (Mounting) — komponenta izveide un ievietošana DOM.
- Constructor
- static getDerivedStateFromProps
- render
- componentDidMount
-
Atjaunināšana (Updating) — notiek, mainoties props vai stāvoklim.
- static getDerivedStateFromProps
- shouldComponentUpdate
- render
- getSnapshotBeforeUpdate
- componentDidUpdate
-
Noņemšana (Unmounting) — komponenta noņemšana no DOM.
- componentWillUnmount
-
Kļūdu apstrāde (Error Handling) — gadījumā, ja rodas kļūdas bērnu komponentos.
- static getDerivedStateFromError
- componentDidCatch
Piemērs, kā izmantot dzīves cikla metodes klases komponentā:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log('Komponents ir uzstādīts');
}
componentDidUpdate(prevProps, prevState) {
console.log('Komponents ir atjaunināts');
}
componentWillUnmount() {
console.log('Komponents tiks noņemts');
}
render() {
return <div>{this.state.count}</div>;
}
}
Funkcionālajās komponentēs ar hookiem līdzīgi posmi tiek īstenoti caur useEffect un citām hook funkcijām.