Compare commits

..

1 Commits

Author SHA1 Message Date
laktionov-as e0597891e1 ErrorBoundary 2026-05-28 21:41:57 +03:00
2 changed files with 101 additions and 33 deletions
+97 -31
View File
@@ -1,45 +1,111 @@
import React, { useMemo, useCallback, useState } from 'react' import React from 'react'
const TodoItem = React.memo(({ item, onToggle, onDelete }) => { class ErrorBoundary extends React.Component {
console.log(`rendred ${item.id}`); constructor(props) {
return <li> super(props);
{item.name} this.state = {hasError: false};
<button onClick={() => onToggle(item.id)}>Done</button> }
<button onClick={() => onDelete(item.id)}>remove</button>
</li>
})
function ItemList({ items }) { static getDerivedStateFromError(error) {
return { hasError: true }
}
const handleToggle = useCallback(id => { componentDidCatch(error,info) {
items.done = true; console.log(error,info);
console.log(`Item ${id} done`) }
console.log(id)
},[]);
const handleDelete = useCallback(id => { handlerReset = () => {
items.pop(id); this.setState({hasError: false});
},[]); }
render() {
if (this.state.hasError) {
return ( return (
<> <div>
<h3>List items</h3> <h1>Что то поломалось</h1>
{items.map(item => ( <button onClick={this.handlerReset}>Повторить</button>
<TodoItem key={item.id} item={item} </div>)
onToggle={handleToggle} onDelete={handleDelete} /> }
))} 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>
)
}
//Если ошибок нет, то рендрим дочерние объекты
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() {
return ( return (
<> <>
{/* Добавьте тестовый контент для проверки */} <h1>Обработка ошибок в компонентах</h1>
<h1>Hello, React!</h1> <ErrorBoundary>
<ItemList items={[ <ProblemComponent />
{id:1,name:'Первый',done:false}, </ErrorBoundary>
{id:2,name:'Второй',done:false} <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>
) )