Compare commits

..

1 Commits

Author SHA1 Message Date
laktionov-as ef33d16373 Сделали React.memo и React.useMemo 2026-05-21 21:33:02 +03:00
2 changed files with 41 additions and 95 deletions
+41 -93
View File
@@ -1,112 +1,60 @@
import React from 'react' import { memo, useState, useMemo } from 'react'
class ErrorBoundary extends React.Component { function memoize(fn) {
constructor(props) { const cache = new Map();
super(props); return function(...args) {
this.state = {hasError: false}; const key = JSON.stringify(args);
} if (cache.has(key)) {
return cache.get(key);
static getDerivedStateFromError(error) {
return { hasError: true }
}
componentDidCatch(error,info) {
console.log(error,info);
}
handlerReset = () => {
this.setState({hasError: false});
}
render() {
if (this.state.hasError) {
return (
<div>
<h1>Что то поломалось</h1>
<button onClick={this.handlerReset}>Повторить</button>
</div>)
} }
return this.props.children; const result = fn.apply(this, args);
cache.set(key,result);
return result;
} }
} }
class AdvancedErrorBoundary extends React.Component { function fibonachi(n, memo={}) {
constructor(props) { if (n in memo) {console.log(n);return memo[n];}
super(props); if (n <= 1) return 1;
this.state = { memo[n] = fibonachi(n-1, memo) + fibonachi(n - 2, memo);
hasError: false, return memo[n];
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 MyComponent = ({ value }) => {
const [counter,setCounter] = React.useState(0) console.log('Rendring');
return <div>{value}</div>
}
const MemoizedComponent = memo(MyComponent);
const Child = memo(({ children }) => {
console.log('Child component rendred');
return <div>{children}</div>;
});
const Parent = () => {
const [count,setCount] = useState(0);
const [text, setText] = useState('');
const handlerClick = () => setCounter(counter + 1) const stableChild = useMemo(() => <span>Memo text</span>,[]);
React.useEffect(() => {
if (counter > 5) {
throw new Error("Ошибка в компоненте");
}
},[counter]);
return ( return (
<div> <>
<h2>Счетчик: {counter}</h2> <Child>
<button onClick={handlerClick}>Прибавить</button> {stableChild}
</div> </Child>
<input type="text" onChange={(e) => setText(e.target.value)} value={text} />
<button onClick={() => setCount(count + 1)}>Increment {count}</button>
</>
) )
} }
function App() { function App() {
return ( return (
<> <>
<h1>Обработка ошибок в компонентах</h1> <h1>Hello, React!</h1>
<ErrorBoundary> <Parent />
<ProblemComponent /> </>
</ErrorBoundary>
<ErrorBoundary>
<ProblemComponent />
</ErrorBoundary>
<ErrorBoundary>
<ProblemComponent />
</ErrorBoundary>
</>
) )
} }
-2
View File
@@ -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>
) )