我遇到一种情况,我需要在页面呈现到服务器端并使用Next.js发送回我之前,先了解用户是否已登录,以避免UI中出现闪烁变化。
我能够弄清楚如果用户已经使用此HOC组件登录,如何防止用户访问某些页面...
export const noAuthenticatedAllowed = (WrappedComponent: NextPage) => {
const Wrapper = (props: any) => {
return <WrappedComponent {...props} />;
};
Wrapper.getInitialProps = async (ctx: NextPageContext) => {
let context = {};
const { AppToken } = nextCookie(ctx);
if (AppToken) {
const decodedToken: MetadataObj = jwt_decode(AppToken);
const isExpired = () => {
if (decodedToken.exp < Date.now() / 1000) {
return true;
} else {
return false;
}
};
if (ctx.req) {
if (!isExpired()) {
ctx.res && ctx.res.writeHead(302, { Location: "/" });
ctx.res && ctx.res.end();
}
}
if (!isExpired()) {
context = { ...ctx };
Router.push("/");
}
}
const componentProps =
WrappedComponent.getInitialProps &&
(await WrappedComponent.getInitialProps(ctx));
return { ...componentProps, context };
};
return Wrapper;
};
这很棒。
现在,我如何构建类似的HOC组件,将其包装起来,比如说“ _app.tsx”,这样我就可以通过获取令牌并确定令牌是否过期并基于它来将“ userAuthenticated”属性传递给每个页面该道具我可以向用户显示适当的UI,而不会产生烦人的闪烁效果?
希望您能为我提供帮助,我尝试按照构建上述HOC的方式进行操作,但是我无法做到这一点,尤其是Typescript不会因其怪异的错误而变得更加轻松:(
Edit == =========================================
我能够创建这样的HOC组件,并userAuthenticated
像下面这样将pro传递到每个页面...
export const isAuthenticated = (WrappedComponent: NextPage) => {
const Wrapper = (props: any) => {
return <WrappedComponent {...props} />;
};
Wrapper.getInitialProps = async (ctx: NextPageContext) => {
let userAuthenticated = false;
const { AppToken} = nextCookie(ctx);
if (AppToken) {
const decodedToken: MetadataObj = jwt_decode(AppToken);
const isExpired = () => {
if (decodedToken.exp < Date.now() / 1000) {
return true;
} else {
return false;
}
};
if (ctx.req) {
if (!isExpired()) {
// ctx.res && ctx.res.writeHead(302, { Location: "/" });
// ctx.res && ctx.res.end();
userAuthenticated = true;
}
}
if (!isExpired()) {
userAuthenticated = true;
}
}
const componentProps =
WrappedComponent.getInitialProps &&
(await WrappedComponent.getInitialProps(ctx));
return { ...componentProps, userAuthenticated };
};
return Wrapper;
};
但是,我必须用此HOC包装每个页面,以便将userAuthenticated
属性传递到我拥有的全局布局,因为我不能用它包装“ _app.tsx”类组件,它总是给我一个Error。 ..
这有效...
export default isAuthenticated(Home);
export default isAuthenticated(about);
但这不是...
export default withRedux(configureStore)(isAuthenticated(MyApp));
因此,必须对每个页面执行此操作,然后将属性传递到每个页面的全局布局中,而不是仅在“ _app.tsx”中执行一次,这有点烦人。
我猜原因可能是因为“ _app.tsx”是类组件而不是像其余页面一样的功能组件?我不知道,我只是在猜测。
有什么帮助吗?
ReactJS
遵循函数式编程或OOP,但是我看到了具有OOP思想的代码在后端开发中的心态。从另一个组件继承一个新类!before我以前没看过。