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) => {
setText(event.target.value);
}
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() { static getDerivedStateFromError(error) {
const countRef = useRef(0); return { hasError: true }
function handlerClick() {
countRef.current += 1;
//alert(`Нажали ${countRef.current} раз.`);
}
return <button onClick={handlerClick}>Нажать</button>;
} }
function TimerComponent() { componentDidCatch(error,info) {
const timerIdRef = useRef(null); console.log(error,info);
useEffect(() => {
timerIdRef.current = setTimeout(() => {
alert("Прошло 3 секунды");
}, 3000);
return () => {
clearTimeout(timerIdRef.current);
}
},[]);
} }
function PrevValue({ value }) { handlerReset = () => {
const prevValueRef = useRef(); this.setState({hasError: false});
}
useEffect(() => { render() {
prevValueRef.current = value; if (this.state.hasError) {
});
return ( return (
<div> <div>
Текущее значение: {value} <br /> <h1>Что то поломалось</h1>
Предыдущее значение: {prevValueRef.current} <button onClick={this.handlerReset}>Повторить</button>
</div>)
}
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 (
<div>
<h2>Произошла ошибка</h2>
<p>Извеняемся, работаем, исправляем. Разработчика привязали к батарее</p>
<button onClick={this.handleReset}>Попробовать снова</button>
</div> </div>
) )
} }
//Если ошибок нет, то рендрим дочерние объекты
function ScrollList() { return this.props.children
const listRef = useRef(null);
const scrollToBottom = () => {
if(listRef.current) {
listRef.current.scrollTop = listRef.current.scrollHeight;
} }
} }
function ProblemComponent() {
const [counter,setCounter] = React.useState(0)
const handlerClick = () => setCounter(counter + 1)
React.useEffect(() => {
if (counter > 5) {
throw new Error("Ошибка в компоненте");
}
},[counter]);
return ( return (
<> <div>
<div ref={listRef} <h2>Счетчик: {counter}</h2>
style={{height: 200, overflowY: 'auto', border: '1px solid black'}}> <button onClick={handlerClick}>Прибавить</button>
{[...Array(20)].map((_,i)=>(
<div key={i}>Элемент {i + 1}</div>
))}
</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>
) )