Compare commits

..

1 Commits

Author SHA1 Message Date
laktionov-as e0597891e1 ErrorBoundary 2026-05-28 21:41:57 +03:00
2 changed files with 92 additions and 77 deletions
+84 -71
View File
@@ -1,98 +1,111 @@
import { useState, useRef, useEffect } from 'react' import React from 'react'
function Example() { class ErrorBoundary extends React.Component {
const myRef = useRef(null); constructor(props) {
const counterRef = useRef(0); super(props);
const [text, setText] = useState(''); this.state = {hasError: false};
useEffect(() => {
myRef.current?.focus();
},[]);
const handlerFocus = () => {
if(myRef.current) {
myRef.current.focus();
} }
};
const handlerChange = (event) => { static getDerivedStateFromError(error) {
setText(event.target.value); return { hasError: true }
} }
counterRef.current += 1;
return <div>
<input ref={myRef} text="text" /><br />
Количество рендров: {counterRef.current}<br />
<input text="text" onChange={handlerChange} value={text} />
<button onClick={handlerFocus}>Поставить фокус на поле</button>
</div>
}
function ClickCounter() { componentDidCatch(error,info) {
const countRef = useRef(0); console.log(error,info);
function handlerClick() {
countRef.current += 1;
//alert(`Нажали ${countRef.current} раз.`);
} }
return <button onClick={handlerClick}>Нажать</button>;
}
function TimerComponent() { handlerReset = () => {
const timerIdRef = useRef(null); this.setState({hasError: false});
useEffect(() => {
timerIdRef.current = setTimeout(() => {
alert("Прошло 3 секунды");
}, 3000);
return () => {
clearTimeout(timerIdRef.current);
} }
},[]);
}
function PrevValue({ value }) { render() {
const prevValueRef = useRef(); if (this.state.hasError) {
useEffect(() => {
prevValueRef.current = value;
});
return ( return (
<div> <div>
Текущее значение: {value} <br /> <h1>Что то поломалось</h1>
Предыдущее значение: {prevValueRef.current} <button onClick={this.handlerReset}>Повторить</button>
</div> </div>)
) }
return this.props.children;
}
} }
function ScrollList() { class AdvancedErrorBoundary extends React.Component {
const listRef = useRef(null); constructor(props) {
super(props);
const scrollToBottom = () => { this.state = {
if(listRef.current) { hasError: false,
listRef.current.scrollTop = listRef.current.scrollHeight; 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 (
<> <div>
<div ref={listRef} <h2>Произошла ошибка</h2>
style={{height: 200, overflowY: 'auto', border: '1px solid black'}}> <p>Извеняемся, работаем, исправляем. Разработчика привязали к батарее</p>
{[...Array(20)].map((_,i)=>( <button onClick={this.handleReset}>Попробовать снова</button>
<div key={i}>Элемент {i + 1}</div> </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> </div>
<button onClick={scrollToBottom}>Прокрутить вниз</button>
</>
) )
} }
function App() { function App() {
return ( return (
<> <>
<h1>Hello, React!</h1> <h1>Обработка ошибок в компонентах</h1>
<ScrollList /> <ErrorBoundary>
<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>
) )