javascript - 如何在 Next.js 中渲染页面之前重定向?
问题描述
我想知道是否可以在 Next.js 中呈现页面之前重定向用户?
现在我有这个:
import { useRouter } from 'next/router';
export default function RedirectPage() {
const router = useRouter();
router.push('/projects');
return (
<div><h1>hi</h1></div>
)
}
出现此错误:Error: No router instance found. you should only use "next/router" inside the client side of your app.
谢谢。
解决方案
您可以使用getServerSideProps通过在返回的对象上设置一个“重定向”属性来实现。
export default function RedirectPage() {
return (
<div><h1>hi</h1></div>
)
}
export async function getServerSideProps(ctx) {
return {
redirect: {
destination: '/projects',
permanent: false,
},
}
}
我不能说这是否会在服务器上呈现页面,但用户将被重定向并且不会显示重定向页面的内容。
推荐阅读
- php - Laravel 在加入一对多时与众不同
- corda - 尝试在多个节点上运行 corda 时出现未知对等错误
- css - 使用 React Native 显示网格 {height : 10, width:10} 作为背景
- ios - 在 UITabBarController 之间传递数据
- python - 使用python解析href
- javascript - IE11 上的weakmap.get 问题
- c# - 通过单击form1上的按钮,它应该显示带有gridview详细信息的form2
- react-native - 如何更新 react-native 项目以适应 iPhone x
- firebase - 如何生成需要用于第三方工具或 SDK 的 PNS 句柄?
- python - 从 2D numpy 数组的每个子数组中获取前 N 个值