reactjs - 欢迎页面/使用 react/next.js 的第一个启动页面
问题描述
你能给我一些只呈现一次的页面示例吗?我想看看其他人是如何实现这个功能的。
因为我使用 next.js,所以我尝试不保存在 localstorage 中,而是使用 cookie 并且它可以工作,但是在 vercel 上的 prod 中我可以看到这个页面,当我不需要时,它会显示 <1s,然后显示正确的页面。
升级版:
它可以工作,但是当我如何使用 vercel 的网站时,会发生这种情况:
第一次
- 显示欢迎页面
- 我按下“NEXT”按钮,然后转到下一页
- 如果我不允许我回去,它会返回到第 2 步的页面
一旦我关闭谷歌标签并重新打开我的网站,我:
- 查看欢迎页面<0.5s
- 我被转移到我最初应该去的页面。
也许这与我使用的 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,
},
};
}
解决方案
我认为您必须在构建时使用getServerSideProps
asgetStaticProps
运行,然后 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
页面必须在某些路线下可用。
推荐阅读
- android - 装有 Android 10 的 Android 盒子上的设备所有者无法正常工作
- jestjs - Expo & Jest:Jest 遇到了意外的令牌
- tfx - TFTransform ValueError:“所有示例工件不存在拆分”
- python - Tensorflow:Module 必须应用在为其实例化的图中
- vb.net - 当datagridview具有复选框列时,使用texbox主动过滤datagridview
- spring-batch - 事务边界中的Spring批处理整个作业
- windows-10 - 在 Window 10 上遇到 git bash 问题,最近的更改使我无法更新它
- ios - 使用 NSTextAttachment 时使用 NSKeyedUnarchiver 在 iOS13 上取消归档 NSAttributedString 时出错
- python - Pandas 数据框比较和复制
- python - 使用 flask-sqlalchemy 组合三个表的动态过滤器