简体   繁体   English

取消订阅事件监听器反应钩子

[英]Unsubscribe from event listener react hooks

In a class-based react component you could simply do;在基于类的反应组件中,您可以简单地做;

componentWillUnmount() {
  window.removeEventListener('resize', this.resizeHandler);
}

Although I am unsure how to do this in a Function Based Component with React Hooks?尽管我不确定如何在带有 React Hooks 的基于函数的组件中执行此操作?

In my application, I perform the function below on a button click in a Component LoginCard .在我的应用程序中,我通过单击 Component LoginCard的按钮来执行以下功能。

const handleLogin = (email, password) => {
  loginService.login(email, password)
    .then((response) => {
      if (!response.error) {
        props.history.push("/");
      }
    });
}

And I wrap the export of LoginCard in a withRouter function from react-router-dom to redirect to the route address.我将LoginCard的导出包装在react-router-domwithRouter函数中,以重定向到路由地址。

export default withRouter(LoginCard);

Inside the LoginCard Component I have a Tabs Component which has the event listener in the useEffect hook.LoginCard组件中,我有一个Tabs组件,它在useEffect钩子中有事件侦听器。

useEffect(() => {
      setUnderLineStyle(getUnderlineStyle());
      window.addEventListener("resize", _.throttle(() => { 
         setUnderLineStyle(getUnderlineStyle())}, 
         300), 
         {passive:true});
   }, [props]);

However, when I click that button in LoginCard and get redirected to / and then resize the window, the function inside the resize event lister setUnderLineStyle(getUnderlineStyle()) gets called.但是,当我在LoginCard单击该按钮并重定向到/然后调整窗口大小时,会调用调整大小事件列表器setUnderLineStyle(getUnderlineStyle())的函数。

I have tried to add the following in useEffect but setUnderLineStyle(getUnderlineStyle()) still gets called on resize.我试图在useEffect添加以下内容,但setUnderLineStyle(getUnderlineStyle())仍然在调整大小时被调用。

return () => window.removeEventListener("resize", _.throttle(() => { 
                setUnderLineStyle(getUnderlineStyle())}, 
                300), 
                {passive:true});

Any ideas?有任何想法吗? Even around a better redirect method to get to / via react-router-dom or how to effectively unsubscribe from event listeners?即使围绕一个更好的重定向方法来获得/通过react-router-dom或如何有效地退订事件监听器?

Make a second useEffect solely for the use of unmounting.制作第二个useEffect仅用于卸载。 Empty dependencies in useEffect make it effectively function as a componentDidMount , and the return of that effectively functions as a componentWillUnmount . useEffect空依赖useEffect使其有效地充当componentDidMount ,并且其返回有效地充当componentWillUnmount

useEffect(() => {
    // Do mounting stuff here

    return () => {
        // Do unmounting stuff here
    };
}, []);

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

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