diff --git a/src/App.jsx b/src/App.jsx index 6bf3ac6..93cd90f 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,10 +1,111 @@ -// удаляем все, оставляя лишь пустую функцию App ниже +import React from 'react' + +class ErrorBoundary extends React.Component { + constructor(props) { + super(props); + this.state = {hasError: false}; + } + + static getDerivedStateFromError(error) { + return { hasError: true } + } + + componentDidCatch(error,info) { + console.log(error,info); + } + + handlerReset = () => { + this.setState({hasError: false}); + } + + render() { + if (this.state.hasError) { + return ( +
+

Что то поломалось

+ +
) + } + return this.props.children; + } +} + +class AdvancedErrorBoundary extends React.Component { + constructor(props) { + super(props); + this.state = { + hasError: false, + error: null, + errorInfo: null + } + } + + static getDerivedStateFromError(error) { + return { hasErorr: true } + } + + componentDidCatch(error, info) { + this.setState({ + error: error, + errorInfo: info + }) + } + + handleReset = () => { + this.setState({ + hasError:false, + error: null, + errorInfo:null + }); + } + + render() { + if(this.state.hasError) { + console.log('Error'); + return ( +
+

Произошла ошибка

+

Извеняемся, работаем, исправляем. Разработчика привязали к батарее

+ +
+ ) + } + //Если ошибок нет, то рендрим дочерние объекты + return this.props.children + } +} + +function ProblemComponent() { + const [counter,setCounter] = React.useState(0) + + const handlerClick = () => setCounter(counter + 1) + + React.useEffect(() => { + if (counter > 5) { + throw new Error("Ошибка в компоненте"); + } + },[counter]); + return ( +
+

Счетчик: {counter}

+ +
+ ) +} function App() { return ( <> - {/* Добавьте тестовый контент для проверки */} -

Hello, React!

+

Обработка ошибок в компонентах

+ + + + + + + + + ) }