![](/img/trans.png)
[英]How to wait for React context to load before loading page in Next.js
[英]How to intercept router before page load in Next.js
我目前在我的下一个项目中使用自定义应用程序_app.ts
。
// import App from 'next/app'
import { useEffect } from "react"
import Router from 'next/router'
function MyApp({ Component, pageProps }) {
useEffect(() => {
const handleRouteChange = url => {
console.log('App is changing to: ', url)
}
Router.events.on('routeChangeStart', handleRouteChange)
return () => {
Router.events.off('routeChangeStart', handleRouteChange)
}
}, [])
return <Component {...pageProps} />
}
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }
export default MyApp
似乎如果我进行硬重新加载,那么如果在浏览器中输入localhost:3000/
,事件将永远不会触发。 如果我输入localhost:3000/test
它也永远不会触发。
似乎它只会在Route.push
调用或<link>
调用时触发
无论如何“拦截”路线,以便我可以在某些条件下在某些路线上重定向用户,如果他们在浏览器上输入路线?
next/router
是客户端路由器。 当您重新加载页面或在浏览器中输入地址时,请求由服务器处理,因此您不会看到routeChangeStart
类的事件。
您可以实现适用于客户端和服务器端路由的客户端重定向。
客户端重定向:
const router = useRouter();
useEffect(() => {
router.push('/redirectLocation');
}, [])
如果您需要在响应浏览器之前在服务器端进行重定向,则必须实现自定义服务器。
我目前在我的下一个项目中使用自定义应用程序_app.ts
。
// import App from 'next/app'
import { useEffect } from "react"
import Router from 'next/router'
function MyApp({ Component, pageProps }) {
useEffect(() => {
const handleRouteChange = url => {
console.log('App is changing to: ', url)
}
Router.events.on('routeChangeStart', handleRouteChange)
return () => {
Router.events.off('routeChangeStart', handleRouteChange)
}
}, [])
return <Component {...pageProps} />
}
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }
export default MyApp
似乎如果我进行硬重新加载,因此如果在浏览器中输入localhost:3000/
,则该事件永远不会触发。 如果我输入localhost:3000/test
它也永远不会触发。
似乎它只会在Route.push
调用或<link>
调用上触发
无论如何“拦截”路由,以便如果用户在浏览器上输入路由,我可以在某些路由的某些条件下重定向用户?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.