Compare commits

..

1 Commits

Author SHA1 Message Date
laktionov-as e0597891e1 ErrorBoundary 2026-05-28 21:41:57 +03:00
+97 -30
View File
@@ -1,44 +1,111 @@
import { useMutation, QueryClientProvider, QueryClient } from '@tanstack/react-query' import React from 'react'
import PostAddForm from './components/PostAddForm'
/* class ErrorBoundary extends React.Component {
const mutation = useMutation({ constructor(props) {
mutationFn: newUser => { super(props);
fetch('https://jsonplaceholder.typicode.com/users', { this.state = {hasError: false};
method: 'GET',
headers: {'Content-type':'application/json'},
body: JSON.stringify(newUser),
}).then(res => res.json())
} }
})
*/
const createQueryClient = () => { static getDerivedStateFromError(error) {
new QueryClient({ return { hasError: true }
defaultOptions: { }
queries: {
staleTime: 5 * 60*1000, componentDidCatch(error,info) {
retry: 1, console.log(error,info);
gcTime: 10*60*1000, }
refetchOnWindowFocus: false,
}, handlerReset = () => {
mutations: { this.setState({hasError: false});
retry:0, }
onError: error => {console.error('Mutation error:',error.message)}
render() {
if (this.state.hasError) {
return (
<div>
<h1>Что то поломалось</h1>
<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>
)
}
//Если ошибок нет, то рендрим дочерние объекты
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>
<QueryClientProvider client={createQueryClient}> <ProblemComponent />
<PostAddForm /> </ErrorBoundary>
</QueryClientProvider> <ErrorBoundary>
<ProblemComponent />
</ErrorBoundary>
<ErrorBoundary>
<ProblemComponent />
</ErrorBoundary>
</> </>
) )
} }