next.js - 在 Next.js 中放置 Router.events 相关代码的位置
问题描述
我只是想知道在哪里可以将 Router.events 相关代码放在 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);
}
...
}
高温高压
推荐阅读
- python - 如何从 Python 调用 Go 函数
- ios - 如何在 iOS 上实用地使用 Expo Cli 杀死 react-native 应用程序?
- mongoose - 如何在猫鼬中删除多个ID
- windows - Maatwebsite 导入在 ubunutu 中不起作用
- bash - 在函数中使用带有 $ 的全局变量和在函数中不使用 $ 有什么区别?
- git - Github - 获取拉取请求作为非暂存更改
- java - 如何找出抽象列表中的对象?
- objective-c - 使用本机模块将 react-native 应用程序的帖子分享到第三方应用程序 instagram
- c++ - std::thread vs pthead,我做错了什么?
- api - Dell Boomi 将 1 个 api 分解为多个?