0

У меня есть два компонента. В зависимости от условия в контейнере рендюрю один из нихНо логика у этих компонентах повторяется Особенно метод componentWillReseiveProps у них одинаковый
и выглядит примерно так

 componentWillReceiveProps(nextProps) {
const { inputType: nextInputType } = nextProps;
const { inputType, values } = this.props;

const { message: nextMessage } = this.getDefaultValues(nextProps.values);

const { message } = this.getDefaultValues(values);

const hasNotChangedInput = nextInputType === inputType;
const hasNotChangedValue = nextMessage === message;

if (hasNotChangedValue && hasNotChangedInput) return;

if (nextInputType === PHONE_STEP_INPUT_MESSAGE) {

    this.handleMessageInputType(nextMessage, nextInputType);
} else if (nextInputType === PHONE_STEP_INPUT_PHONE) {

    this.handleMobileInputType(nextMessage, nextInputType);
} else if (nextInputType === PHONE_STEP_INPUT_HYBRID) {

    this.handleHybridInputType(nextMessage, nextInputType);
}

}

Как лучше избавиться от дублирования componentWillReceiveProps в данном случае?

2
  • Базовый класс написать для них не пробовали?.. 16 апр 2018 в 12:46
  • каким образом? может быть у вас есть пример какой-то...
    – werty
    16 апр 2018 в 13:23

1 ответ 1

1

Можно написать high order component и вынести общую логику туда.

import React from 'react'

const withCommonLogic = Component => {
    return class extends React.Component {
          componentWillReceiveProps(nextProps) {
              // общая логика
          }

          render() {
              return <Component {...this.props} />
          }
    }
}

Теперь достаточно обернуть нужный компонент в этот hoc

const MyComp = props => <div></div>

export default withCommonLogic(MyComp)
4
  • А если. У каждого контейнера своим mapStateToProps И mapDispatchToProps Куда их поместить?
    – werty
    16 апр 2018 в 11:07
  • @werty connect можно обернуть так же, connect(...)(withCommonLogic(MyComp)) 16 апр 2018 в 11:59
  • @werty решение помогло? 29 апр 2018 в 9:51
  • 1
    да. спасибо....!!
    – werty
    29 апр 2018 в 14:14

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.