Skip to content
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

junior course react #26

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
97 changes: 97 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"classnames": "^2.2.6",
"csssr-school-utils": "git+https://github.com/CSSSR-School/junior-course-utils.git",
"react": "^16.12.0",
"react-addons-shallow-compare": "^15.6.2",
"react-dom": "^16.12.0",
"react-scripts": "3.2.0"
},
Expand Down
22 changes: 11 additions & 11 deletions public/index.css
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

margin: 0;
padding: 0;
color: #323c48;
font-family: Open Sans, -apple-system, BlinkMacSystemFont, "Segoe UI",
"Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans",
"Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

3 changes: 1 addition & 2 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">
</div>
<div id="root"></div>
</body>
</html>
18 changes: 18 additions & 0 deletions src/BaseComponent/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React from 'react';
import shallowCompare from 'react-addons-shallow-compare';

import { logger } from 'csssr-school-utils';

class BaseComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
if (shallowCompare(this, nextProps, nextState)) {
logger.call(this, this.constructor.name, nextProps, nextState);

return true;
}

return false;
}
}

export default BaseComponent;
5 changes: 5 additions & 0 deletions src/FilterContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from 'react';

const FiltersContext = React.createContext({});

export default FiltersContext;
70 changes: 70 additions & 0 deletions src/PriceFilter/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import PropTypes from 'prop-types';
import React from 'react';

import BaseComponent from '../BaseComponent/index';
import FiltersContext from '../FilterContext';

const filterTitleStyle = {
marginBottom: '8px',
fontSize: '20px',
fontWeight: 700
}

const labelStyle = {
marginRight: '16px'
}

const labelTitleStyle = {
marginRight: '8px'
}

const inuputStyle ={
width: '6em'
}

class PriceFilter extends BaseComponent {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Думаю уже нет смысла наследоваться от BaseComponent, эта часть была для понимания как sCU реализуется. Наследуйся от React.Component

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне самому инетресно пока, когда был рерндер
Давай оставим :)


handleControlChange(filterName, value) {
setTimeout(() => this.props.onChangeFilter({

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вся асинхронщина должнв быть в componentDidMount

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это задержка пользовательского ввода
Чтобы фильтрация не происходила мгновенно после ввода каждого символа

filterName,
value
}), 500);
}

render() {
return (
<div>
<div style={ filterTitleStyle }>
<span>Цена</span>
</div>
<FiltersContext.Consumer>
{
({ minPrice, maxPrice }) =>
<div>
<label style={ labelStyle }>
<span style={ labelTitleStyle }>От:</span>
<input style={ inuputStyle }
type="text"
defaultValue={ minPrice || 0 }
onChange={(event)=> this.handleControlChange('minPrice', parseInt(event.target.value, 10))}/>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В целом в этом случае стрелки ок. Но это часто приводит в проблемам "лишних" рендеров тк функция анонимная каждый раз.
Нужно это иметь ввиду.
https://ru.reactjs.org/docs/faq-functions.html#arrow-function-in-render тут подробнее

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

обратил внимание, для реакта это повод перерисовать компонент, ввиду того, что ссылка изменилась
в конкретной ситуации передаём minPrice как аргумент

</label>

<label style={ labelStyle }>
<span style={ labelTitleStyle }>До:</span>
<input style={ inuputStyle }
type="text"
defaultValue={ maxPrice || 0 }
onChange={(event)=> this.handleControlChange('maxPrice', parseInt(event.target.value, 10))}/>
</label>
</div>
}
</FiltersContext.Consumer>
</div>
)
}
}

PriceFilter.propTypes = {
onChangeFilter: PropTypes.func
}
export default PriceFilter
37 changes: 37 additions & 0 deletions src/UserFilters/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import React from 'react';
import PropTypes from 'prop-types';

import BaseComponent from '../BaseComponent/index';
import PriceFilter from '../PriceFilter/index';

const filtersContainerStyle = {
padding: '4px 16px'
}

class UserFilters extends BaseComponent {
constructor(props) {
super(props);
this.handleFilterChange = this.handleFilterChange.bind(this);
}

handleFilterChange(changes) {
const { filterName, value } = changes;

setTimeout(() => this.props.onChangeFilter({

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вообще не очень понятно зачем тут таймаут

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нужна задержка по вводу пользователя
правда ей тут немного не метсто

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

уберу ка я это от сюда

[filterName]: value
}), 500)
}

render() {
return (
<div style={ filtersContainerStyle }>
<PriceFilter onChangeFilter={ this.handleFilterChange }/>
</div>
)
}
}

UserFilters.propTypes = {
onChangeFilter: PropTypes.func
}
export default UserFilters;
Loading