Сделали компонент с фотографией

This commit is contained in:
2026-06-02 20:23:09 +03:00
parent 5ee1bf2eee
commit 6827c800f1
+24 -10
View File
@@ -1,30 +1,44 @@
import React from 'react'
class Clock extends React.Component {
class RandomUser extends React.Component {
constructor(props) {
super(props)
this.state = { time: new Date().toLocaleTimeString() }
this.state = { user: {} }
}
componentDidMount() {
this.timerId = setInterval(()=>{
this.setState({ time: new Date().toLocaleTimeString() })
}, 1000);
console.log('Таймер смонтирован')
fetch('https://randomuser.me/api')
.then(responce => responce.json())
.then(json => this.setState({ user: json.results[0] }));
console.log('смонтирован')
}
componentDidUpdate(prevProps,prevState) {
console.log(this.state);
console.log('Компонент обнвлен')
}
componentWillUnmount() {
clearInterval(this.timerId)
console.log('Компонент таймера размонтирован')
}
render() {
return <div>
<h2>Текущее время: {this.state.time}</h2>
{this.state.user &&
this.state.user.name &&
(
<>
<h2>{this.state.user.name.first} {this.state.user.name.last}</h2>
<img src={this.state.user.picture.medium} />
<button onClick={() => {
console.log('Загружаем ... ')
fetch('https://randomuser.me/api')
.then(responce => responce.json())
.then(json => this.setState({ user: json.results[0] }));
}}>Загрузить нового</button>
</>
)
}
</div>
}
}
@@ -34,11 +48,11 @@ function App() {
return (
<>
<h1>Жизненный цикл компонента часов</h1>
<h1>Домашнее задание: жизненый цикл</h1>
<button onClick={()=> setShowClock(!showClock)}>
{showClock ? 'Скрыть часы' : 'Показать часы' }
</button>
{showClock && <Clock />}
{showClock && <RandomUser />}
</>
)
}