首页 > 解决方案 > 欢迎页面/使用 react/next.js 的第一个启动页面

问题描述

你能给我一些只呈现一次的页面示例吗?我想看看其他人是如何实现这个功能的。

因为我使用 next.js,所以我尝试不保存在 localstorage 中,而是使用 cookie 并且它可以工作,但是在 vercel 上的 prod 中我可以看到这个页面,当我不需要时,它会显示 <1s,然后显示正确的页面。

升级版:

它可以工作,但是当我如何使用 vercel 的网站时,会发生这种情况:

第一次

  1. 显示欢迎页面
  2. 我按下“NEXT”按钮,然后转到下一页
  3. 如果我不允许我回去,它会返回到第 2 步的页面

一旦我关闭谷歌标签并重新打开我的网站,我:

  1. 查看欢迎页面<0.5s
  2. 我被转移到我最初应该去的页面。

也许这与我使用的 cookie 有关

把这个页面的实现:

const firstTime = cookies(props).firstLaunch;

  useEffect(() => {
    const expire = new Date(new Date().getTime() + 7776000000000);
    if (firstTime === undefined) {
      document.cookie = `firstLaunch=false; expires=` + expire;
    }
    alert(localStorage.firstLaunch);
  }, [firstTime]);

  if (firstTime === "false") return <LoadingPage title={""} to={"/map"} />;
  return (
    ... <=== welcome page


async function getStaticProps(ctx) {
  return {
    props: {
      firstLaunch: cookies(ctx).firstLaunch,
    },
  };
}

标签: reactjsnext.js

解决方案


我认为您必须在构建时使用getServerSidePropsasgetStaticProps运行,然后 cookie 不可用。在开发模式下有点不同 - 每次更改都会重新呈现静态页面,因此它可能看起来可以正常工作。

尝试这个:

export async function getServerSideProps() {
   const parsedCookies = cookie.parse(context.req.headers.cookie);

   if (!parsedCookies.firstLaunch) {
     return {
       redirect: {
         permanent: false,
         destination: '/first-launch',
       },
     }
   }
}

这样您就可以在服务器端重定向用户而无需任何内容闪烁(0.5 秒)。但是,您的firstLaunch页面必须在某些路线下可用。


推荐阅读