简体   繁体   English

使用带有 next.js 的反应路由器

[英]using react router with next.js

I am learning how to use Next.js/React for my application.我正在学习如何在我的应用程序中使用 Next.js/React。 I am currently researching the topic of routing and I had a few questions.我目前正在研究路由的主题,我有几个问题。 I know that you can use react-router for React (I used vue-router before).我知道你可以将 react-router 用于 React(我之前使用过 vue-router)。 However, I do not know if I need to use react-router with Next.js and how I would use it if I could.但是,我不知道是否需要将 react-router 与 Next.js 一起使用,如果可以的话,我将如何使用它。 I am currently using a pages directory to hold pages to redirect to.我目前正在使用页面目录来保存要重定向到的页面。 How can I redirect to different pages in React/Next?如何重定向到 React/Next 中的不同页面?

Here is some sample code to implement it in:这是一些实现它的示例代码:

Class Login extends Component {

  state = {
    user: {},
  }

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

}

After yippee, I want to redirect to /home which is in the pages folder.在 yippee 之后,我想重定向到 pages 文件夹中的 /home。

For your first question I need to say: No, you don't need react-router in Nextjs it will use something called file-system based router which you can read more about it here对于您的第一个问题,我需要说:不,您不需要react-router中的Nextjs它将使用称为基于文件系统的路由器的东西,您可以在此处阅读有关它的更多信息

So after you set up your routes if you want to Navigate to them you have two options:因此,在您设置好路线后,如果您想导航到它们,您有两个选择:

first using the Link Component from next/link : more about it here首先使用来自next/linkLink组件:更多信息在这里

second using the router from next/router which you can Navigate around like useHistory from react-router : more about it here第二次使用来自next/routerrouter ,您可以像useHistory中的react-router一样导航:这里有更多信息

example from the doc:文档中的示例:

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

So in your case, using this is how you can redirect:因此,在您的情况下,使用以下方法可以重定向:

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)

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

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