简体   繁体   English

react-scroll 在每次滚动时创建事件监听器

[英]react-scroll creates event listeners on each scroll

I use react-scroll to move the user smoothly down the site on click but there is a problem.我使用 react-scroll 在点击时将用户平稳地移到网站上,但有一个问题。

Why are additional event listeners (3 to 5) created every time animateScroll.scrollToBottom is clicked?为什么每次单击animateScroll.scrollToBottom时都会创建额外的事件侦听器(3 到 5 个)? Checked in chrome dev-tools.检查了 chrome 开发工具。 Does this not contribute to loss of performance?这不会导致性能损失吗? After unmounting the component event listeners are not removed.卸载组件后,事件侦听器不会被删除。

import React from 'react';
import { animateScroll } from 'react-scroll';

import { Container, TextWrapper, Text, TextLink, ArrowWrapper, Arrow } from './styles/header';

export default function Header({ children, ...restProps }) {
  return <Container {...restProps}>{children}</Container>;
}

Header.TextWrapper = function HeaderTextWrapper({ children, ...restProps }) {
  return <TextWrapper {...restProps}>{children}</TextWrapper>;
};

Header.Text = function HeaderText({ children, ...restProps }) {
  return <Text {...restProps}>{children}</Text>;
};

Header.TextLink = function HeaderTextLink({ children, ...restProps }) {
  return <TextLink {...restProps}>{children}</TextLink>;
};

Header.Arrow = function HeaderArrow({ ...restProps }) {
  return (
    <ArrowWrapper {...restProps} onClick={animateScroll.scrollToBottom}>
      <Arrow />
      <Arrow />
      <Arrow />
    </ArrowWrapper>
  );
};

I think your issue since you are try to write component as a props like Header.Text, this will re-render every time the component is called!我认为您的问题是因为您尝试将组件编写为 Header.Text 之类的道具,每次调用组件时都会重新渲染!

Simply to reduce this issue, put the components in Header direact,, and just pass the value.只是为了减少这个问题,把组件直接放在 Header 中,然后传递值。 no need to update its every time...不需要每次都更新...

For example:例如:

export default function HeaderText(props) {
  return <h1></h1>
}
export default function HeaderBody(props) {
  return <p>Body</p>
}
    export default function Header(props) {
      return <Container>
       <HeaderText />
       <HeaderBody />
    </Container>;
    }

No react will handle render base on any change on component which its need to render again...任何反应都不会根据需要再次渲染的组件上的任何更改来处理渲染...

Another note, if you need to set a function inside component and need to prevent re-render for it you can use useCallBack for funcation and useMemo for return value needed like:另一个注意事项,如果您需要在组件内部设置 function 并且需要防止重新渲染它,您可以使用 useCallBack 进行功能,使用 useMemo 来获取所需的返回值,例如:

const text = useMemo(() => {return <Link to=""> Test </Link>}, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM