Compare commits

..

2 Commits

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