Compare commits

..

1 Commits

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