Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2775fc8283 | |||
| c9759fbfc7 |
+69
-84
@@ -1,111 +1,96 @@
|
|||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
import styles from './App.module.scss'
|
||||||
|
|
||||||
class ErrorBoundary extends React.Component {
|
class Clock extends React.Component {
|
||||||
constructor(props) {
|
constructor(props) {
|
||||||
super(props);
|
super(props);
|
||||||
this.state = {hasError: false};
|
this.state = { date: new Date() };
|
||||||
}
|
}
|
||||||
|
componentDidMount() {
|
||||||
static getDerivedStateFromError(error) {
|
this.timerId = setInterval( () => this.tick(), 1000);
|
||||||
return { hasError: true }
|
|
||||||
}
|
}
|
||||||
|
componentWillUnmount() {
|
||||||
componentDidCatch(error,info) {
|
clearInterval(this.timerId)
|
||||||
console.log(error,info);
|
|
||||||
}
|
}
|
||||||
|
tick() {
|
||||||
handlerReset = () => {
|
this.setState({ date: new Date() })
|
||||||
this.setState({hasError: false});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
if (this.state.hasError) {
|
return <div>{this.state.date.toLocaleTimeString()}</div>
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h1>Что то поломалось</h1>
|
|
||||||
<button onClick={this.handlerReset}>Повторить</button>
|
|
||||||
</div>)
|
|
||||||
}
|
|
||||||
return this.props.children;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class AdvancedErrorBoundary extends React.Component {
|
function Clock2() {
|
||||||
constructor(props) {
|
const [date, setDate] = React.useState(new Date());
|
||||||
super(props);
|
|
||||||
this.state = {
|
|
||||||
hasError: false,
|
|
||||||
error: null,
|
|
||||||
errorInfo: null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static getDerivedStateFromError(error) {
|
React.useEffect(()=>{
|
||||||
return { hasErorr: true }
|
const timerId = setInterval(()=> setDate(new Date()),1000);
|
||||||
}
|
return () => clearInterval(timerId);
|
||||||
|
},[])
|
||||||
|
|
||||||
componentDidCatch(error, info) {
|
return <div>{date.toLocaleTimeString()}</div>
|
||||||
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() {
|
function MouseTracker() {
|
||||||
const [counter,setCounter] = React.useState(0)
|
const [x,setX] = React.useState(0);
|
||||||
|
const [y,setY] = React.useState(0);
|
||||||
|
|
||||||
const handlerClick = () => setCounter(counter + 1)
|
const mouseMoveHandler = event => {
|
||||||
|
setX(event.clientX);
|
||||||
|
setY(event.clientY);
|
||||||
|
}
|
||||||
|
|
||||||
|
React.useEffect(()=>{
|
||||||
|
document.addEventListener('mousemove', mouseMoveHandler);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousemove',mouseMoveHandler);
|
||||||
|
}
|
||||||
|
},[]);
|
||||||
|
|
||||||
|
return <div className={styles.container}>
|
||||||
|
<p>Координаты мыши:<br /> X:<b>{x}</b>, Y:<b>{y}</b></p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataFetcher() {
|
||||||
|
const [posts,setPosts] = React.useState([]);
|
||||||
|
const [users,setUsers] = React.useState([]);
|
||||||
|
|
||||||
|
const getPosts = async () => {
|
||||||
|
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
|
||||||
|
const data = await response.json();
|
||||||
|
setUsers(data.reduce((acc, value) => {
|
||||||
|
if (!(value.userId in acc))
|
||||||
|
return [...acc,value.userId]
|
||||||
|
return acc
|
||||||
|
}))
|
||||||
|
console.log(users);
|
||||||
|
setPosts(data.slice(1,10));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (counter > 5) {
|
console.log("Компонент создан");
|
||||||
throw new Error("Ошибка в компоненте");
|
getPosts();
|
||||||
}
|
return () => {console.log("Компонент удален");setPosts([])};
|
||||||
},[counter]);
|
},[])
|
||||||
return (
|
|
||||||
<div>
|
return <div><ol>{posts.map(post => <li id={post.id}>{post.title}</li>)}</ol></div>
|
||||||
<h2>Счетчик: {counter}</h2>
|
|
||||||
<button onClick={handlerClick}>Прибавить</button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
|
const [tracker,setTracker] = React.useState(false);
|
||||||
|
const [dataFetcher,setDataFetcher] = React.useState(false);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<h1>Обработка ошибок в компонентах</h1>
|
<h1>Hello, React!</h1>
|
||||||
<ErrorBoundary>
|
<Clock />
|
||||||
<ProblemComponent />
|
<Clock2 />
|
||||||
</ErrorBoundary>
|
<button onClick={() => setTracker(!tracker)}>Показать/Скрыть трекер</button>
|
||||||
<ErrorBoundary>
|
{ tracker && <MouseTracker /> }
|
||||||
<ProblemComponent />
|
<button onClick={() => setDataFetcher(!dataFetcher)}>Показать/Скрыть посты</button>
|
||||||
</ErrorBoundary>
|
{ dataFetcher && <DataFetcher /> }
|
||||||
<ErrorBoundary>
|
|
||||||
<ProblemComponent />
|
|
||||||
</ErrorBoundary>
|
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
.container {
|
||||||
|
width: 300px;
|
||||||
|
height: 200px;
|
||||||
|
border: 2px dashed grey;
|
||||||
|
margin: 10px;
|
||||||
|
text-align: center;
|
||||||
|
p {
|
||||||
|
margin-top: 20%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Reference in New Issue
Block a user