Skip to content

Hw 3 #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions classworks/lesson-3/_babelrc

This file was deleted.

18 changes: 0 additions & 18 deletions classworks/lesson-3/index.html

This file was deleted.

128 changes: 128 additions & 0 deletions classworks/lesson-3/lifecycle_methods_theory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import React, { Component } from "react";
import { YoutubeSearch } from "путь к компоненту YoutubeSearch";
const API_KEY = 'some long key';//ключ для апи ютуба

class App extends Component {
state = {
appName: 'Title',
}

constructor(props) {
super(props);

}

// componentDidMount вызывается, когда компонент отрендерился.
// Хорошее место для обращений к ДОМ и запросов на сервер
componentDidMount() {
setTimeout(() => {
this.setState({
appName: 'Hello from componentWillReceiveProps'
}, 10000)
})
}

render() {
return (
<main>
<YoutubeSearch
title={this.state.appName} //после 10 секунд здесь вместо изначального 'Title' появится 'Hello from componentWillReceiveProps'
onBlurFunc={term => {
//console.log('something')// тут лучше делать запрос на сервер
YTSearch({ key: API_KEY, term }, data => { // при онблуре с инпута происходит запрос к апи
console.log(data);
})
}/>
</main>
)
}
}

//---YoutubeSearch class ----------------------------------
import React, { Component } from "react";

export class YoutubeSearch extends Component {
constructor(props) { // если собираемся где-то использовать пропсы, нужно писать так
super(props);

this.state = {
inputValue: '',
title: props.title,// изначально 'Title'
isActive: false
}

}


//WillReceiveProps вызывается, когда пропсы уже пришли, но компонент еще не отрендерился
// при изначальном рендере не вызывается
componentWillReceiveProps(nextProps){
console.log('props', this.props); // те пропсы, которые еще не изменились из-за сеттаймаута,
// т.е. здесь title="Title", onBlur=function(){...}
console.log('nextProps', nextProps); // те пропсы, которые пришли после сеттаймаута,
// т.е. title="Hello from componentWillReceiveProps", onBlur=function(){...}
//функцию мы не меняли, она в обоих случаях одинаковая
// это используется, если стейт зависит от пропсов. Тут обычно проверяют, изменилось что-то или нет.
// типа значение в новых пропсах больше предыдущего или что-то такое
// или если в пропсах ничего не изменилось, компонент не нужно перереднеривать
// тут принимается решение, нужно ли эти новые пропсы куда-то дальше передавать
if (nextProps.title != this.state.title) { // "Hello from componentWillReceiveProps" != "Title"
this.setState({
inputValue: nextProps.title
})
}

}

//shouldComponentUpdate вызывается после того, как сработал componentWillReceiveProps, мы там сделали setState
// и теперь принимаем решение, перерендеривать компонент или нет
// при изначальном рендере не вызывается
shouldComponentUpdate(nextProps, nextState) {
// возвращает true or false. Если true - компонент перерендерится, если false - то нет
// все оптимизации производят здесь
}

//conponentWillUpdate вызывается после shouldComponentUpdate
conponentWillUpdate(){

}

//conponentDidUpdate вызывается после conponentWillUpdate тогда, когда компонент был обновлен
conponentDidUpdate(){

}

//conponentWillUnmount вызывается перед тем, как компонент будет удален
conponentWillUnmount(){

}

onChange = event => {
this.setState({
inputValue: event.target.value
})
};

onBlur = () => {
this.props.onBlurFunc(this.state.inputValue);//вызываем ф-цию onBlur, которая пришла в пропсах из Апп
//и передаем в нее велью из инпута, т.е. по сути происходит запрос к Апи ютуба с тем значением, которое ввели в инпуте
this.setState({isActive: false})
};

render() {
const { inputValue } = this.state;
return (
<div>
<h3>{this.state.title}</h3>
<input
value={inputValue}
onBlur={this.onBlur}
onChange={this.onChange}
onFocus={() => {
this.setState({isActive: true})
}}
/>
</div>
)
}
}
25 changes: 0 additions & 25 deletions classworks/lesson-3/package.json

This file was deleted.

41 changes: 0 additions & 41 deletions classworks/lesson-3/src/main.js

This file was deleted.

23 changes: 0 additions & 23 deletions classworks/lesson-3/webpack.config.js

This file was deleted.

21 changes: 21 additions & 0 deletions classworks/lesson-3/www/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.

# dependencies
/node_modules

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
Loading