将页面重定向到 url Next.JS

Kil*_*ogs 2 javascript url redirect next.js

我有一个运行 next.js 的简单网页,该页面仅返回“Hello World”元素,我希望它将我重定向到另一个 URL (youtube)。

它基本上是加载时的重定向页面。

我的简单页面:

function Home() {
    return <div>Hello World</div>
}

export default Home
Run Code Online (Sandbox Code Playgroud)

我什至尝试了js window.location 函数,但无济于事

Pac*_*cka 7

您可以使用ex加载页面后next.js重定向:Router

import Router from 'next/router'

componentDidMount(){
    const {pathname} = Router
    if(pathname == '/' ){
       Router.push('/hello-nextjs')
    }
}
Run Code Online (Sandbox Code Playgroud)

或者使用钩子:

import React, { useEffect } from "react";
...
useEffect(() => {
   const {pathname} = Router
   if(pathname == '/' ){
       Router.push('/hello-nextjs')
   }
 });
Run Code Online (Sandbox Code Playgroud)