代码之家  ›  专栏  ›  技术社区  ›  ThunD3eR

在react中卸载组件时未删除侦听器

  •  2
  • ThunD3eR  · 技术社区  · 8 年前

    我已经在react.js中构建了一个spa,我正在使用react router dom、react redux和一些其他模块。

    我使用react router dom和switch组件。

    我的路线:

    const allRoutes = [
        {
          path: "/Intro",
          name: "Intro",
          component: Intro
        },
        {
          path: "/Room",
          name: "Room",
          component: Room
        },
        {
          path: "/Simulation",
          name: "Simulation",
          component: Simulation
        },
        {
          path: "/Cartypes",
          name: "Cartypes",
          component: CarTypes
        },
        {
          path: "/StartPosition",
          name: "StartPosition",
          component: StartPosition
        },
        {
          path: "/Movment",
          name: "Movment",
          component: Movment
        },
        { redirect: true, path: "/", to: "/Intro", name: "Intro" }
      ];
    
      export default allRoutes;
    

    我如何渲染它们。

              <Switch>
                  {routes.map((prop, key) => {
                    if (prop.redirect)
                        return <Redirect from={prop.path} to={prop.to} key={key} />;
                    return (
                      <Route path={prop.path} component={prop.component} key={key} />
                    );
    
                  })}
              </Switch>
    

    脚本 :

    在我的一个组件中,我想检测用户何时离开那个特定的组件,url何时更改。

    为此,我发现我可以借助 withRouter 访问检测url更改的listner。我把这个放在组件里

      componentWillMount() {
        this.unlisten = this.props.history.listen((location, action) => {
          console.log("on route change");
          console.log(location)
          console.log(action)
        });
      }
    

    一旦用户更改了url,就会触发指定的……但是。 假设我在“/simulation”,这是我监听任何url更改的地方。当我移动到“/room”时,component中的代码将装载到“/simulation”组件中,现在我使用一个新的url…

    问题 :如果我现在将从“/room”更改为“/intro”,则“/simulation”下的componentwillmount中的相同代码将再次执行。

    有人能告诉我为什么吗?又如何阻止它几次行刑呢?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Shubham Khatri    8 年前

    发生这种情况的原因是,一旦组件卸载,您就没有清除历史侦听器,当组件卸载时,您需要清除侦听器,您将在 componentWillUnmount 生命周期法 Simulation 喜欢

    componentWillUnmount() {
        this.unlisten();
    }
    
        2
  •  0
  •   ThunD3eR    8 年前

    上面的答案是正确的…但是我发现在

    componentWillUnmount
    

    问题是我输入的代码 componentWillMount 自从 componentWillUnmount 先被处决/更快。

    所以我最终得到了如下结论:

      componentWillMount() {
        this.unlisten = this.props.history.listen((location, action) => {
          // execute my code
          this.unlisten(); // unregister the listner. 
        });
      }