Compare commits

..

1 Commits

Author SHA1 Message Date
laktionov-as e0597891e1 ErrorBoundary 2026-05-28 21:41:57 +03:00
2 changed files with 89 additions and 84 deletions
+87 -84
View File
@@ -1,108 +1,111 @@
import React from 'react' import React from 'react'
class MyComponent extends React.Component { class ErrorBoundary extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { data: null }; this.state = {hasError: false};
this.handleClick = this.handleClick.bind(this); }
static getDerivedStateFromError(error) {
return { hasError: true }
}
componentDidCatch(error,info) {
console.log(error,info);
}
handlerReset = () => {
this.setState({hasError: false});
} }
render() { render() {
return ( if (this.state.hasError) {
<div> return (
{this.state.data ? ( <div>
<div>Данные: {this.state.data}</div> <h1>Что то поломалось</h1>
) : ( <button onClick={this.handlerReset}>Повторить</button>
<div>Загрузка...</div> </div>)
)} }
<button onClick={this.handleClick}>Обновить</button> return this.props.children;
</div>
)
}
componentDidMount() {
fetch('https://api.example.com/data')
.then(responce => responce.json())
.then(json => this.setState({data: json}));
this.timerId = setInterval(()=> console.log('Tick'), 1000);
}
componentWillUnmout() {
clearInterval(this.timerId);
}
handleClick() {
this.setState({data: 'Данные'})
} }
} }
class MyComponent2 extends React.Component { class AdvancedErrorBoundary extends React.Component {
controller = new AbortController() constructor(props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null
}
}
componentDidMount() { static getDerivedStateFromError(error) {
fetch('https://api.example.com/data',{ singnal: this.controller.signal }) return { hasErorr: true }
.then(responce => responce.json()) }
.then(json => this.setState({data: json}))
.catch(error => { componentDidCatch(error, info) {
if(error.name == 'AbortError') { this.setState({
console.log('Aborted'); error: error,
} else { errorInfo: info
console.log('Other error',error); })
} }
handleReset = () => {
this.setState({
hasError:false,
error: null,
errorInfo:null
}); });
} }
componentWillUnmount() {
this.controller.abort()
}
}
class MyComponent3 extends React.Component {
componentDidMount() {
this.loadData();
}
async loadData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
this.setSate({ data });
} catch {
console.log('error');
}
}
}
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 }
}
componentDidMount() {
console.log('Timer mounted');
this.interval = setInterval(()=>{
this.setState(prevState => ({seconds: prevState.seconds + 1}))
},1000);
}
componentWillUnmount() {
console.log('Timer unmount');
clearInterval(this.interval);
}
render() { render() {
return <h2>Прошло секунд: {this.state.seconds}</h2> if(this.state.hasError) {
console.log('Error');
return (
<div>
<h2>Произошла ошибка</h2>
<p>Извеняемся, работаем, исправляем. Разработчика привязали к батарее</p>
<button onClick={this.handleReset}>Попробовать снова</button>
</div>
)
}
//Если ошибок нет, то рендрим дочерние объекты
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 (
<div>
<h2>Счетчик: {counter}</h2>
<button onClick={handlerClick}>Прибавить</button>
</div>
)
}
function App() { function App() {
const [show,setShow] = React.useState(true);
return ( return (
<> <>
<h1>Таймер с классом</h1> <h1>Обработка ошибок в компонентах</h1>
<button onClick={()=>setShow(prev => !prev)}>{show ? 'Скрыть' : 'Показать'} таймер</button> <ErrorBoundary>
{show && <Timer />} <ProblemComponent />
</ErrorBoundary>
<ErrorBoundary>
<ProblemComponent />
</ErrorBoundary>
<ErrorBoundary>
<ProblemComponent />
</ErrorBoundary>
</> </>
) )
} }
+2
View File
@@ -4,5 +4,7 @@ import { createRoot } from 'react-dom/client'
import App from './App.jsx' import App from './App.jsx'
createRoot(document.getElementById('root')).render( createRoot(document.getElementById('root')).render(
<StrictMode>
<App /> <App />
</StrictMode>
) )