Jul*_*tte 6 javascript routes reactjs react-router 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!');
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
在 yippee 之后,我想重定向到页面文件夹中的 /home 。
对于你的第一个问题,我需要说:不,你不需要react-router使用Nextjs称为基于文件系统的路由器的东西,你可以在这里阅读更多相关信息
因此,在设置路线后,如果您想导航到这些路线,您有两个选择:
首先使用Link以下组件next/link:更多相关信息请参见此处
第二个使用 ,您可以像routerfrom一样next/router进行导航:更多相关信息请参见此处useHistoryreact-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
Run Code Online (Sandbox Code Playgroud)
因此,就您而言,可以使用以下方法进行重定向:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12108 次 |
| 最近记录: |