首页 > 解决方案 > 在 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/(然后转到错误页面)

我怎样才能阻止这种行为?

标签: next.js

解决方案


我相信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();
}

推荐阅读