Compare commits

..

3 Commits

+41 -42
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); componentDidMount() {
return result; fetch('https://randomuser.me/api')
.then(responce => responce.json())
.then(json => this.setState({ user: json.results[0] }));
console.log('смонтирован')
} }
}
function fibonachi(n, memo={}) { componentDidUpdate(prevProps,prevState) {
if (n in memo) {console.log(n);return memo[n];} console.log(this.state);
if (n <= 1) return 1; console.log('Компонент обнвлен')
memo[n] = fibonachi(n-1, memo) + fibonachi(n - 2, memo); }
return memo[n];
}
const MyComponent = ({ value }) => { componentWillUnmount() {
console.log('Rendring'); console.log('Компонент таймера размонтирован')
return <div>{value}</div> }
}
const MemoizedComponent = memo(MyComponent); render() {
return <div>
const Child = memo(({ children }) => { {this.state.user &&
console.log('Child component rendred'); this.state.user.name &&
return <div>{children}</div>; (
});
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 />}
</> </>
) )
} }