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