ComponentWillUnmount 方法永远不会被调用

问题描述 投票:0回答:1

我正在开发一个简单的反应应用程序,包含以下页面:

export default class App extends Component {
...

render(){
    return (
      <Router>
        <Navbar.../>
        <Switch>
           ...
          <Route
            exact
            path="/project"
            render={(props) => (
              <Project .../>
            )}
          />)
        }
}

我想在每次用户退出项目组件时进行检测,以执行一些逻辑。我尝试使用

componentWillUnmount
方法如下:

class Project extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: true,
    };
  }

  componentWillUnmount(){
    console.log("hello, world!")
  }
...
}

问题是,该方法永远不会被调用:当我尝试刷新页面时,更改 url ecc,有任何提示吗?

反应版本:^18.3.1 反应路由器版本:5.2.0

谢谢

javascript reactjs react-router create-react-app
1个回答
0
投票

重新加载页面基本上意味着“转储当前页面”并重新加载,React应用程序和组件没有机会卸载。您可以利用

beforeunload
侦听器来运行一些逻辑,以防用户重新加载整个页面或页面因任何其他原因卸载(就像它们完全导航出您的应用程序,导航到另一个域/页面等。 ).

class Project extends Component {
  ...

  // unload event callback handler
  unloadHandler = () => {
    console.log("hello, world!");
  };

  componentDidMount() {
    // instantiate unload event listener
    window.addEventListener("beforeunload", this.unloadHandler);
  }

  componentWillUnmount() {
    // remove unload event listener when component just unmounts
    window.removeEventListener("beforeunload", this.unloadHandler);

    // manually call handler to run the same logic
    this.unloadHandler();
  }

  ...
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.