next.js - 在 NextJS 中停止缓存重定向
问题描述
query
如果我没有找到代码参数,我想将用户重定向到错误页面
import { useEffect } from 'react';
import { useRouter } from 'next/router';
export default function Home(props){
const router = useRouter();
useEffect(() => {
if(!props.code){
console.log('No code found');
router.push('/error');
}
});
// call an api passing the code
return (
<>
<div>Something</div>
</>
)
}
export async function getServerSideProps(context) {
context.res.setHeader('Cache-Control', 'No-Cache');
return {
props: { code: context.query.code || null }
}
}
如果用户使用 url 访问此页面,localhost:3000/
则应将其重定向到localhost:3000/error
,但如果用户带有特定的查询参数localhost:3000/?code=1234
,则不得重定向用户。
问题是当我在没有参数的情况下测试这个组件到 URL 时code
,我正确地重定向到错误页面 ( localhost:3000/error
),但是在此之后,如果我输入 url localhost:3000/?code=1234
,我也会重定向到错误页面。
当我在匿名窗口中尝试此操作时,我在转到localhost:3000/?code=1234
后正确重定向localhost:3000/
(然后转到错误页面)
我怎样才能阻止这种行为?
解决方案
我相信useEffect
当组件安装在浏览器中时,您的代码应该只运行一次。
useEffect(() => {
if(!props.code){
console.log('No code found');
router.push('/error');
}
},[]);
或者,您可以立即在内部重定向getServerSideProps
export const getServerSideProps = async (context) => {
const { res } = context;
// if there is no code do the redirect
res.writeHead(301, { location: "https://google.com" } );
res.end();
}
推荐阅读
- java - Hibernate 数据库 (maria-db) 更改检测
- kotlin - 具有非数值的对象框 notIn
- python - Python:将整数转换为数据时间戳
- android - 应用程序未激活时,应用程序图标未显示通知
- android - 有没有办法检测我当前的 wifi 是否与之前连接的 wifi 不同?
- c# - 是否可以从自己的 getter 中的数组类型属性中获取索引
- python - ValueError: int() 基数为 16 的无效文字:''
- sql-server - 在 Sql Server 中解析以下 XML 时出错
- arrays - 如何在 swift 中在 NSArray 中的空值索引中附加新值
- r - 折线图未在 R 中以 plotly 显示