Оптимизировать массив компонентов, у которых есть слушатели событий окна - PullRequest
0 голосов
/ 27 декабря 2018

У меня есть массив данных, который необходим для рендеринга массива одного и того же компонента, который имеет прослушиватель событий окна.Но если у нас есть 20 слушателей событий на странице, то у нас супер замораживание на странице.Как иметь один прослушиватель событий в массиве одного и того же компонента?

Many event listeners

class BmResponsiveMenuButton extends PureComponent {
  lastWidth = 0
  resizeStep = 0
  state = {
    hidden: false
  }

  componentDidMount() {
  //HERE ADDING EVENT LISTENERS (TOTALLY WE HAVE 15-20 LISTENERS ON PAGE)
    window.addEventListener('resize', this.handleResize)
    window.addEventListener('scroll', this.handleScroll, false)
    this.anchorMenuButton = document.getElementById(this.props.moreMenuButtonId)
  }

  handleResize = () => {
    this.handleHiddenOrNot()
  }

  componentDidUpdate() {
    this.lastWidth = document.documentElement.clientWidth
  }

  handleHiddenOrNot = () => {
    this.resizeStep = Math.abs(this.lastWidth - document.documentElement.clientWidth)

    let boundingMenu = this.anchorMenuButton.getBoundingClientRect()
    let boundingButton = this.anchorEl.getBoundingClientRect()
    if (boundingButton.right > boundingMenu.left - 10) {
      this.setState({
        hidden: true
      })
      this.props.onHide(this.props.id)
    } else {
      this.setState({
        hidden: false
      })
      this.props.onUnHide(this.props.id)
    }
  }

  handleScroll = () => {
    this.handleResize()
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize)
    window.removeEventListener('scroll', this.handleScroll, false)
  }

  handleExited = () => {
    let elem = this.anchorEl
    elem.style.opacity = '0'
    elem.style.visibility = 'hidden'
  }

  handleEnter = () => {
    let elem = this.anchorEl
    elem.style.opacity = '1'
    elem.style.visibility = 'visible'
    elem.style.position = 'sticky'
  }
  render() {
    const {
      title,
      url,
      classes,
      target,
      effects,
      effectType,
      index,
      active,
      currentModule,
      module
    } = this.props
    const transitionProps = {
      key: title,
      in: !this.state.hidden,
      enter: true,
      exit: true,
      timeout: !effects ?
        0 : {
          enter: this.resizeStep > 200 ? index * 100 : 300,
          exit: 200
        },
      onEnter: () => this.handleEnter(),
      onExited: () => this.handleExited()
    }
    let activeModule
    if (module && currentModule === module) {
      activeModule = true
    } else if (active) {
      activeModule = active
    } else {
      activeModule = url.includes(window.location.pathname + window.location.search + window.location.hash)
    }
    const ButtonComponent = ( <
      Link to = {
        url
      }
      target = {
        target
      }
      innerRef = {
        (node) => (this.anchorEl = node)
      } >
      <
      Button className = {
        classNames(classes.topNavigationButton, activeModule ? classes.selected : '')
      } > {
        title
      } <
      /Button> < /
      Link >
    )
    switch (effectType) {
      case 'slide':
        return ( <
          Slide direction = {
            'left'
          } { ...transitionProps
          } > {
            ButtonComponent
          } <
          /Slide>
        )

      case 'fade':
        return <BmFade { ...transitionProps
        } > {
          ButtonComponent
        } < /BmFade>

      case 'grow':
        return <BmGrow { ...transitionProps
        } > {
          ButtonComponent
        } < /BmGrow>

      default:
        break
    }
  }
}

Отредактировано на примере кода.Я использую этот компонент для отображения или скрытия кнопки, если она не помещается в окне.Я комментирую место, где я создаю eventListeners

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...