Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 12515f925d | |||
| b3662b759f |
+81
-84
@@ -1,111 +1,108 @@
|
|||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
|
||||||
class ErrorBoundary extends React.Component {
|
class MyComponent extends React.Component {
|
||||||
constructor(props) {
|
constructor(props) {
|
||||||
super(props);
|
super(props);
|
||||||
this.state = {hasError: false};
|
this.state = { data: null };
|
||||||
}
|
this.handleClick = this.handleClick.bind(this);
|
||||||
|
|
||||||
static getDerivedStateFromError(error) {
|
|
||||||
return { hasError: true }
|
|
||||||
}
|
|
||||||
|
|
||||||
componentDidCatch(error,info) {
|
|
||||||
console.log(error,info);
|
|
||||||
}
|
|
||||||
|
|
||||||
handlerReset = () => {
|
|
||||||
this.setState({hasError: false});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
if (this.state.hasError) {
|
return (
|
||||||
return (
|
<div>
|
||||||
<div>
|
{this.state.data ? (
|
||||||
<h1>Что то поломалось</h1>
|
<div>Данные: {this.state.data}</div>
|
||||||
<button onClick={this.handlerReset}>Повторить</button>
|
) : (
|
||||||
</div>)
|
<div>Загрузка...</div>
|
||||||
}
|
)}
|
||||||
return this.props.children;
|
<button onClick={this.handleClick}>Обновить</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
fetch('https://api.example.com/data')
|
||||||
|
.then(responce => responce.json())
|
||||||
|
.then(json => this.setState({data: json}));
|
||||||
|
|
||||||
|
this.timerId = setInterval(()=> console.log('Tick'), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
componentWillUnmout() {
|
||||||
|
clearInterval(this.timerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleClick() {
|
||||||
|
this.setState({data: 'Данные'})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class AdvancedErrorBoundary extends React.Component {
|
class MyComponent2 extends React.Component {
|
||||||
constructor(props) {
|
controller = new AbortController()
|
||||||
super(props);
|
|
||||||
this.state = {
|
componentDidMount() {
|
||||||
hasError: false,
|
fetch('https://api.example.com/data',{ singnal: this.controller.signal })
|
||||||
error: null,
|
.then(responce => responce.json())
|
||||||
errorInfo: null
|
.then(json => this.setState({data: json}))
|
||||||
}
|
.catch(error => {
|
||||||
}
|
if(error.name == 'AbortError') {
|
||||||
|
console.log('Aborted');
|
||||||
static getDerivedStateFromError(error) {
|
} else {
|
||||||
return { hasErorr: true }
|
console.log('Other error',error);
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidCatch(error, info) {
|
|
||||||
this.setState({
|
|
||||||
error: error,
|
|
||||||
errorInfo: info
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
handleReset = () => {
|
|
||||||
this.setState({
|
|
||||||
hasError:false,
|
|
||||||
error: null,
|
|
||||||
errorInfo:null
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
componentWillUnmount() {
|
||||||
|
this.controller.abort()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class MyComponent3 extends React.Component {
|
||||||
|
componentDidMount() {
|
||||||
|
this.loadData();
|
||||||
|
}
|
||||||
|
|
||||||
render() {
|
async loadData() {
|
||||||
if(this.state.hasError) {
|
try {
|
||||||
console.log('Error');
|
const response = await fetch('https://api.example.com/data');
|
||||||
return (
|
const data = await response.json();
|
||||||
<div>
|
this.setSate({ data });
|
||||||
<h2>Произошла ошибка</h2>
|
} catch {
|
||||||
<p>Извеняемся, работаем, исправляем. Разработчика привязали к батарее</p>
|
console.log('error');
|
||||||
<button onClick={this.handleReset}>Попробовать снова</button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
//Если ошибок нет, то рендрим дочерние объекты
|
|
||||||
return this.props.children
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function ProblemComponent() {
|
class Timer extends React.Component {
|
||||||
const [counter,setCounter] = React.useState(0)
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
this.state = { seconds: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
const handlerClick = () => setCounter(counter + 1)
|
componentDidMount() {
|
||||||
|
console.log('Timer mounted');
|
||||||
|
this.interval = setInterval(()=>{
|
||||||
|
this.setState(prevState => ({seconds: prevState.seconds + 1}))
|
||||||
|
},1000);
|
||||||
|
}
|
||||||
|
|
||||||
React.useEffect(() => {
|
componentWillUnmount() {
|
||||||
if (counter > 5) {
|
console.log('Timer unmount');
|
||||||
throw new Error("Ошибка в компоненте");
|
clearInterval(this.interval);
|
||||||
}
|
}
|
||||||
},[counter]);
|
render() {
|
||||||
return (
|
return <h2>Прошло секунд: {this.state.seconds}</h2>
|
||||||
<div>
|
}
|
||||||
<h2>Счетчик: {counter}</h2>
|
|
||||||
<button onClick={handlerClick}>Прибавить</button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
|
const [show,setShow] = React.useState(true);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<h1>Обработка ошибок в компонентах</h1>
|
<h1>Таймер с классом</h1>
|
||||||
<ErrorBoundary>
|
<button onClick={()=>setShow(prev => !prev)}>{show ? 'Скрыть' : 'Показать'} таймер</button>
|
||||||
<ProblemComponent />
|
{show && <Timer />}
|
||||||
</ErrorBoundary>
|
|
||||||
<ErrorBoundary>
|
|
||||||
<ProblemComponent />
|
|
||||||
</ErrorBoundary>
|
|
||||||
<ErrorBoundary>
|
|
||||||
<ProblemComponent />
|
|
||||||
</ErrorBoundary>
|
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user