Middle
Kāpēc dzīves cikla metodes nevar definēt, izmantojot bultiņas funkcijas?
sobes.tech AI
Atbilde no AI
React klases komponentos dzīves cikla metodes nedrīkst definēt ar bultiņas funkcijām, jo tas novedīs pie this sasaistes ar pašreizējo kontekstu (parasti globālo vai undefined stingrā režīmā), nevis ar komponenta instanci. React izsauc šīs metodes ar noteiktu this kontekstu, kas jānorāda uz komponenta instanci, lai piekļūtu props, state un komponenta metodēm.
class MyComponent extends React.Component {
// Pareizi: 'this' būs komponenta instance
componentDidMount() {
console.log(this.props);
}
// Nepareizi: 'this' nebūs komponenta instance, kad to izsauks React
componentDidUpdate = () => {
// Šeit 'this' ir saistīts ar kontekstu, kurā tika definēta bultiņas funkcija,
// kas, visticamāk, nav komponenta instance, kad to izsauc React.
console.log(this.state);
}
}