使用本指南解决了它。
TL:DR 基本上我在成功验证码后将令牌添加到本地存储,令牌是访问表单页面所必需的。
创建了一个名为 withAuth 的 HOC
import { useRouter } from "next/router";
const withAuth = (WrappedComponent: any) => {
return (props: JSX.IntrinsicAttributes) => {
// checks whether we are on client / browser or server.
if (typeof window !== "undefined") {
const Router = useRouter();
const accessToken = localStorage.getItem("accessToken");
// If there is no access token we redirect to "/" page.
if (!accessToken) {
Router.replace("/");
return null;
}
// If this is an accessToken we just render the component that was passed with all its props
return <WrappedComponent {...props} />;
}
// If we are on server, return null
return null;
};
};
export default withAuth;
更改验证码页面以在每次加载时清理本地存储,并在成功输入后放入令牌。
function Captcha() {
const reRef = useRef<ReCAPTCHA>(null);
const router = useRouter()
if(process.browser){localStorage.clear()}
return (
<div className={styles.container}>
<h1>Подтвердите, что вы не робот</h1>
<ReCAPTCHA
sitekey={`${process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}`}
size="normal"
ref={reRef}
onChange={() =>
{
localStorage.setItem("accessToken" , "1"),
router.push('/form')
}
}
/>
</div>
);
}
export default Captcha;
并将我的表单组件传递给 withAuth(从导出默认主页更改)
export default withAuth(Home);