繁体   English   中英

Next Js Router.push 不是函数错误

[英]Next Js Router.push is not a function error

当我尝试使用 Router.push() 重定向时,出现以下错误:

TypeError: next_router__WEBPACK_IMPORTED_MODULE_3__.Router.push is not a function

我正在尝试从 create-react-app 迁移到下一个 js。

const redirectUser = () => {
        if (true) {
            Router.push('/');
        }
    };

我不得不像这样导入:

// works
import Router from "next/router";
// dont
import { Router } from "next/router";

路由器模块仅在客户端可用

当你使用 next.js 时你必须考虑到重定向应该在getInitialProps方法中以避免不必要的渲染组件。

例如

const MyComponent = ()=>{
  return <tag> {/* ... */} </tag>
}
MyComponent.getInitialProps = ({res}) => {
  if (res) { 
    /* serve-side */
    res.writeHead(302, {
    Location: 'http://example.com'
  })
  res.end()
  } else {      
   /* client-side */
    Router.push('http://example.com')
  }
  return {}
}

从 next/router 导入 Router 时不要添加大括号

用这个:

import Router from "next/router";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM