Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将页面重定向到url Next.JS_Javascript_Url_Redirect_Next.js - Fatal编程技术网

Javascript 将页面重定向到url Next.JS

Javascript 将页面重定向到url Next.JS,javascript,url,redirect,next.js,Javascript,Url,Redirect,Next.js,我有一个运行next.js的简单网页,该网页只返回“helloworld”元素,我希望它将我重定向到另一个URL(youtube) 加载时,它基本上是一个重定向页面 我的简单页面: function Home() { return <div>Hello World</div> } export default Home 函数Home(){ 返回你好世界 } 导出默认主页 我甚至尝试了js window.location功能,但在next.js中无效。加载页面

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

加载时,它基本上是一个重定向页面

我的简单页面:

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

export default Home
函数Home(){
返回你好世界
}
导出默认主页

我甚至尝试了js window.location功能,但在
next.js

中无效。加载页面后,您可以使用
路由器重定向,例如:

import Router from 'next/router'

componentDidMount(){
    const {pathname} = Router
    if(pathname == '/' ){
       Router.push('/hello-nextjs')
    }
}
或带挂钩:

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

next.js
中,您可以在页面加载后使用
Router
重定向,例如:

import Router from 'next/router'

componentDidMount(){
    const {pathname} = Router
    if(pathname == '/' ){
       Router.push('/hello-nextjs')
    }
}
或带挂钩:

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

为了在服务器端呈现时重定向页面,可以将其放在/pages/文件中导出函数的底部,并设置if条件。例如,如果该页面不存在,它将重定向到其他页面

这样,您就不必玩
路线。按

if (!pageData) {
    res.statusCode = 301;
    res.setHeader("location", "/page-you-want-to-redirect-to");
    res.end();
    return {props: {notFound: true}};
}

Export default Page

为了在服务器端呈现时重定向页面,可以将其放在/pages/文件中导出函数的底部,并设置if条件。例如,如果该页面不存在,它将重定向到其他页面

这样,您就不必玩
路线。按

if (!pageData) {
    res.statusCode = 301;
    res.setHeader("location", "/page-you-want-to-redirect-to");
    res.end();
    return {props: {notFound: true}};
}

Export default Page

我建议使用
useRouter
代替hooks方法。我建议使用
useRouter
代替hooks方法。