【问题标题】:Redirecting to new page in class component of ReactJS using Next使用 Next 重定向到 ReactJS 的类组件中的新页面
【发布时间】:2021-11-24 17:59:43
【问题描述】:

我的项目建立在 ReactJS 类组件之上。我不知道 NextJS,不幸的是我也不擅长 react-router。但是,我尝试了一些方法。

import React, { Component } from 'react';
import useRouter from 'next/router';

    class App extends Component {
    
        Router = useRouter()

        render() {
        return <div>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
             <button  onClick={() => Router.push('https://www.google.com/')}> Join </button>
          </div>
        </div>
      }
    }
    
    export default App;

我知道这是错误的,因此出现错误。在这里,我只想在单击按钮后重定向到谷歌主页。请帮忙。

【问题讨论】:

  • 你遇到了什么错误?
  • React Hook "useRouter" 不能在顶层调用。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用
  • 不,它没有。我正在为一个包含 100 多个组件的大型现场项目提出一个小概念。
  • 您提到的错误引用了useRouter,但这不在您发布的代码中。你能提供一个实际的minimal reproducible example吗?

标签: reactjs next.js


【解决方案1】:

你像这样导入内置的下一个路由器:

import {useRouter} from 'next/router'

// const router = useRouter() - inside a componenet

然后你做:

router.push('...')

编辑

对了,你为什么不直接使用&lt;a href='google.com'&gt;Google&lt;/a&gt;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2020-09-06
  • 2022-11-07
  • 1970-01-01
  • 2019-03-31
  • 2013-09-23
  • 1970-01-01
相关资源
最近更新 更多