首页 > 解决方案 > 在 Next.js 中放置 Router.events 相关代码的位置

问题描述

我只是想知道在哪里可以将 Router.events 相关代码放在 Next.js 中?显然,我不能把它放在一个特定的组件中,因为它需要在整个应用程序中使用。

谢谢你。

标签: next.js

解决方案


您可以将它放在用于初始化每个页面的自定义 App 组件中。

https://github.com/zeit/next.js#custom-app

下面是一些订阅和取消订阅路由器事件的示例代码:

const eventHandler = (url) => {...};

export default class MyApp extends App {
    constructor(props) {
        super(props);

        Router.events.on("routeChangeComplete", eventHandler);
    }

    componentWillUnmount(){
        Router.events.off("routeChangeComplete", eventHandler);
    }

    ...
}

高温高压


推荐阅读