将 React 路由器与 next.js 一起使用
using react router with next.js
我正在学习如何将 Next.js/React 用于我的应用程序。我目前正在研究路由主题,我有几个问题。我知道你可以为 React 使用 react-router(我之前使用过 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。
对于你的第一个问题,我需要说:不,你不需要 react-router
in Nextjs
它将使用一种叫做基于文件系统的路由器的东西,你可以阅读更多关于它的信息 here
因此,如果您想 导航 到它们,那么在设置路线后,您有两个选择:
首先 使用 next/link
中的 Link
组件:更多信息 here
second 使用 next/router
中的 router
,您可以像 react-router
中的 useHistory
一样导航:更多信息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)
我正在学习如何将 Next.js/React 用于我的应用程序。我目前正在研究路由主题,我有几个问题。我知道你可以为 React 使用 react-router(我之前使用过 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。
对于你的第一个问题,我需要说:不,你不需要 react-router
in Nextjs
它将使用一种叫做基于文件系统的路由器的东西,你可以阅读更多关于它的信息 here
因此,如果您想 导航 到它们,那么在设置路线后,您有两个选择:
首先 使用 next/link
中的 Link
组件:更多信息 here
second 使用 next/router
中的 router
,您可以像 react-router
中的 useHistory
一样导航:更多信息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)