[英]using react router with next.js
我正在学习如何在我的应用程序中使用 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。
对于您的第一个问题,我需要说:不,您不需要react-router
中的Nextjs
它将使用称为基于文件系统的路由器的东西,您可以在此处阅读有关它的更多信息
因此,在您设置好路线后,如果您想导航到它们,您有两个选择:
首先使用来自next/link
的Link
组件:更多信息在这里
第二次使用来自next/router
的router
,您可以像useHistory
中的react-router
一样导航:这里有更多信息
文档中的示例:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.