Compare commits

..

2 Commits

+30 -45
View File
@@ -1,59 +1,44 @@
import { memo, useState, useMemo } from 'react' import React from 'react'
function memoize(fn) { class Clock extends React.Component {
const cache = new Map(); constructor(props) {
return function(...args) { super(props)
const key = JSON.stringify(args); this.state = { time: new Date().toLocaleTimeString() }
if (cache.has(key)) {
return cache.get(key);
} }
const result = fn.apply(this, args);
cache.set(key,result); componentDidMount() {
return result; this.timerId = setInterval(()=>{
this.setState({ time: new Date().toLocaleTimeString() })
}, 1000);
console.log('Таймер смонтирован')
} }
}
function fibonachi(n, memo={}) { componentDidUpdate(prevProps,prevState) {
if (n in memo) {console.log(n);return memo[n];} console.log('Компонент обнвлен')
if (n <= 1) return 1; }
memo[n] = fibonachi(n-1, memo) + fibonachi(n - 2, memo);
return memo[n];
}
const MyComponent = ({ value }) => { componentWillUnmount() {
console.log('Rendring'); clearInterval(this.timerId)
return <div>{value}</div> console.log('Компонент таймера размонтирован')
} }
const MemoizedComponent = memo(MyComponent); render() {
return <div>
const Child = memo(({ children }) => { <h2>Текущее время: {this.state.time}</h2>
console.log('Child component rendred'); </div>
return <div>{children}</div>; }
});
const Parent = () => {
const [count,setCount] = useState(0);
const [text, setText] = useState('');
const stableChild = useMemo(() => <span>Memo text</span>,[]);
return (
<>
<Child>
{stableChild}
</Child>
<input type="text" onChange={(e) => setText(e.target.value)} value={text} />
<button onClick={() => setCount(count + 1)}>Increment {count}</button>
</>
)
} }
function App() { function App() {
const [showClock, setShowClock] = React.useState(true);
return ( return (
<> <>
<h1>Hello, React!</h1> <h1>Жизненный цикл компонента часов</h1>
<Parent /> <button onClick={()=> setShowClock(!showClock)}>
{showClock ? 'Скрыть часы' : 'Показать часы' }
</button>
{showClock && <Clock />}
</> </>
) )
} }