Skip to content

Refactoring#1

Open
gentslava wants to merge 8 commits intomasterfrom
feature/refactoring
Open

Refactoring#1
gentslava wants to merge 8 commits intomasterfrom
feature/refactoring

Conversation

@gentslava
Copy link
Copy Markdown
Member

@gentslava gentslava commented Feb 28, 2024

Рефакторинг компонента.
История изменений https://github.com/rosstrah/frontend-test/pull/1/commits

@gentslava gentslava changed the title Feature - Refactoring Refactoring Feb 28, 2024
Copy link
Copy Markdown
Member Author

@gentslava gentslava left a comment

Choose a reason for hiding this comment

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

Комментарии по ревью


const showError = (internalErrors, errorsServer) => {
useEffect(() => {
if (!errorsServer && !errorsServer.isArray()) return null;
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Потенциальная ошибка. Базово в js у объектов нет метода isArray().
Здесь несколько вариантов:

  • Это ошибка и предполагается Array.isArray(errorsServer).
  • Этот метод определен в объекте errorsServer.
  • Этот метод определен через прототипирование.

Нужно понимать, какой у нас случай.
По хорошему, вопросов бы не возникло, если бы errorsServer был подробно типизирован, а не просто errorsServer: PropTypes.array.
Для этих целей нужно подробнее через propTypes расписать поля объекта, либо использовать ts.

} = props;

const showError = (internalErrors, errorsServer) => {
useEffect(() => {
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Перенес в useEffect, чтобы не было лишних срабатываний на каждый рендер.

sendAgentCard,
// surnameSuggestions,
// firstNameSuggestions,
// patronymicSuggestions,
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Комментарии обязательно удаляем. Все есть в git.

</FormRow>
</>
)}
{false && props.username === userInfo.username && (
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Пусть false не смущает. Его убирать не нужно, раз вопросов о нерабочей функциональности не возникала.
Это банально отключённая функциональность = закомментированный код. Не долго думая, удаляем.

}
});
};
}, [internalErrors, errorsServer]);
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Вообще в этой функции происходят мутации объектов, что является анти паттерном React. Дочерний компонент мутирует объекты, которые приходят из родительского компонента. Такое сложно отлаживать, если дочерний компонент занесет ошибку.
Учитывая, что здесь просто происходят какие-то пробросы из одних ключей в другие, имеет смысл эти ключи добавить в валидатор, а данную функцию просто выпилить.

whatsappBotEnable: "Подключить бота Whatsapp",
whatsappNotifyDisable: "Отключить уведомления Whatsapp",
whatsappNotifyEnable: "Подключить уведомления Whatsapp",
juridicalError: "Если вы хотите работать как юридическое лицо, то необходимо заключить с нами договор. Для этого вам нужно обратиться в тех. поддержку по телефону +7 (800) 550-50-43, либо написать на почту docs@rosstrah.ru, в теме письма указав свой логин",
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Отображаемый текст выносим по той же причине. Плюс есть потенциал для локализации на разные языки.

verificationPhoneModal: "verificationPhoneModal",
success: "success",
error: "error",
text: "text",
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Константные строки лучше вынести в константы, чтобы сложнее было опечататься в названиях и было проще отладить такого типа ошибки.

value={userInfo.email}
onChange={(value) => setValue([MAGIC_STRINGS.userInfo, MAGIC_STRINGS.email], value)}
onBlur={(value) => {
validate(MAGIC_STRINGS.email, value);
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Функции в onChange, onBlur можно вынести в отдельные хендлеры. Тогда компонент будет чище, логика и отображение будут разделены.

@@ -0,0 +1,146 @@
import React, { memo } from "react";
import moment from "moment";
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Библиотека moment.js deprecated. Можно использовать более легковесную библиотеку day.js

if (loading) return (
<EmptyNoBorder>
<Spinner />
</EmptyNoBorder>
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

<EmptyNoBorder><Spinner /></EmptyNoBorder>
можно вынести в отдельный компонент <Loader />, который будет в UI-kit проекта.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant