Sınıf bileşeni yapısı
- React kursu
- Orta seviye
- Ders 54/80
- 4 dk
getDerivedStateFromError ve componentDidCatch kullanmayı öğrenirsin.
Sınıf bileşeni yapısı
Error boundary'nin iskeleti üç parçadan oluşur: state (hasError), getDerivedStateFromError ve render. State hata durumunu, metot hata yakalamayı, render ise çizimi belirler.
State başlangıçta false olur. Hata fırlatıldığında getDerivedStateFromError true döndürür; React state'i günceller ve render yeniden çalışır.
componentDidCatch ise hata sonrası çalışır; hata kaydı veya analiz araçlarına bildirim için kullanılır.
componentDidCatch
componentDidCatch(error, info) metodu hata yakalandıktan sonra çalışır. İki parametre alır: hata nesnesi ve bileşen yığını bilgisi. Yan etki yapmak için uygundur.
Örnek kullanım: hatayı bir izleme servisine göndermek, kullanıcıya mesaj göstermek veya hatayı konsola yazdırmak. Bu metot state güncellemez; onu getDerivedStateFromError yapar.
İki metodu birlikte kullanmak yaygındır: biri state, diğeri kayıt. React bu ayrımı performans için zorunlu kılar.
Uygulama componentDidCatch ekle
Aşağıdaki iskeleti tamamla. ErrorBoundary sınıfı yaz; getDerivedStateFromError(error) ve componentDidCatch(error, info) metotları içerir, render hasError doğruysa <h1>Hata</h1> değilse this.props.children döndürür. Dışa aktar.
Başlangıç kodu
import { Component } from "react";
// ErrorBoundary sınıfını buraya yazÖrnek çözüm
import { Component } from "react";
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log(error, info);
}
render() {
if (this.state.hasError) return <h1>Hata</h1>;
return this.props.children;
}
}
export default ErrorBoundary;Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 getDerivedStateFromError ne döndürür?
- Bir dizi
- Bir dize
- Bir state nesnesi Doğru cevap
- Bir sayı
Açıklama: getDerivedStateFromError bir state nesnesi döndürür.
2 State başlangıcı
class ErrorBoundary extends Component {
state = { hasError: ____ };
}
class ErrorBoundary extends Component {
state = { hasError: false };
}
Açıklama: hasError başlangıçta false olur; hata sırasında true olur.
3 Sınıf bileşeni yapısı: kavramları eşleştir
| Kavram | Anlamı |
|---|---|
getDerivedStateFromError |
State günceller |
componentDidCatch |
Yan etki yapar |
hasError |
Hata durumu |
render |
Çizimi belirler |