Compare commits

..

3 Commits

+39 -40
View File
@@ -1,59 +1,58 @@
import { memo, useState, useMemo } from 'react' import React from 'react'
function memoize(fn) { class RandomUser extends React.Component {
const cache = new Map(); constructor(props) {
return function(...args) { super(props)
const key = JSON.stringify(args); this.state = { user: {} }
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key,result);
return result;
}
} }
function fibonachi(n, memo={}) { componentDidMount() {
if (n in memo) {console.log(n);return memo[n];} fetch('https://randomuser.me/api')
if (n <= 1) return 1; .then(responce => responce.json())
memo[n] = fibonachi(n-1, memo) + fibonachi(n - 2, memo); .then(json => this.setState({ user: json.results[0] }));
return memo[n]; console.log('смонтирован')
} }
const MyComponent = ({ value }) => { componentDidUpdate(prevProps,prevState) {
console.log('Rendring'); console.log(this.state);
return <div>{value}</div> console.log('Компонент обнвлен')
} }
const MemoizedComponent = memo(MyComponent); componentWillUnmount() {
console.log('Компонент таймера размонтирован')
}
const Child = memo(({ children }) => { render() {
console.log('Child component rendred'); return <div>
return <div>{children}</div>; {this.state.user &&
}); this.state.user.name &&
(
const Parent = () => {
const [count,setCount] = useState(0);
const [text, setText] = useState('');
const stableChild = useMemo(() => <span>Memo text</span>,[]);
return (
<> <>
<Child> <h2>{this.state.user.name.first} {this.state.user.name.last}</h2>
{stableChild} <img src={this.state.user.picture.medium} />
</Child> <button onClick={() => {
<input type="text" onChange={(e) => setText(e.target.value)} value={text} /> console.log('Загружаем ... ')
<button onClick={() => setCount(count + 1)}>Increment {count}</button> fetch('https://randomuser.me/api')
.then(responce => responce.json())
.then(json => this.setState({ user: json.results[0] }));
}}>Загрузить нового</button>
</> </>
) )
} }
</div>
}
}
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 && <RandomUser />}
</> </>
) )
} }