【问题标题】:using react router with next.js使用带有 next.js 的反应路由器
【发布时间】:2021-06-26 16:47:36
【问题描述】:

我正在学习如何将 Next.js/React 用于我的应用程序。我目前正在研究路由的主题,我有几个问题。我知道你可以将 react-router 用于 React(我之前使用过 vue-router)。但是,我不知道是否需要将 react-router 与 Next.js 一起使用,以及如果可以的话我将如何使用它。我目前正在使用页面目录来保存要重定向到的页面。如何在 React/Next 中重定向到不同的页面?

下面是一些实现它的示例代码:

Class Login extends Component {

  state = {
    user: {},
  }

  loginUser = (e) => {
      loginUser(this.state.user)
        .then(response => {
          console.log(response);
          if (response['username']) {
            console.log('yippee!');
          }
      });
  }

}

在 yippee 之后,我想重定向到 pages 文件夹中的 /home。

【问题讨论】:

标签: javascript reactjs routes react-router next.js


【解决方案1】:

对于您的第一个问题,我需要说:不,您不需要在 Nextjs 中使用 react-router,它将使用基于文件系统的路由器,您可以阅读更多关于它的信息 here

因此,在您设置好路线后,如果您想导航到它们,您有两个选择:

首先使用来自next/linkLink组件:更多关于它here

第二使用来自next/routerrouter,您可以像useHistory 一样从react-router 导航:更多关于它here

文档中的示例:

import { useRouter } from 'next/router'

function ActiveLink({ children, href }) {
  const router = useRouter()
  const style = {
    marginRight: 10,
    color: router.asPath === href ? 'red' : 'black',
  }

  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

export default ActiveLink

因此,在您的情况下,您可以使用以下方式进行重定向:

import { withRouter } from 'next/router'

Class Login extends Component {

  state = {
    user: {},
  }

  loginUser = (e) => {
      loginUser(this.state.user)
        .then(response => {
          console.log(response);
          if (response['username']) {
            console.log('yippee!');
            //here is what you need:
            this.props.router.push('/your-route');
          }
      });
  }

}

export default withRouter(Login)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-23
    • 2016-04-24
    • 2018-12-14
    • 2020-08-24
    • 2016-09-10
    • 2018-06-03
    • 2020-09-08
    • 2017-05-19
    相关资源
    最近更新 更多