【发布时间】:2020-03-04 03:44:38
【问题描述】:
我找不到使用 next.js 在服务器端和客户端获取 isAuthenticated 变量常量值的方法
我正在使用自定义 app.js 将应用程序包装在 Apollo Provider 中。我正在使用布局来显示用户是否经过身份验证。 defaultPage 是一个 HOC 组件。
当页面是服务器端时,isAuthenticated 设置为 true。但是一旦我更改页面 - 这是客户端渲染(不重新加载) - isAuthenticated 一直保持未定义状态,直到我重新加载页面。
_app.js
import App from 'next/app';
import React from 'react';
import withData from '../lib/apollo';
import Layout from '../components/layout';
class MyApp extends App {
// static async getInitialProps({ Component, router, ctx }) {
// let pageProps = {};
// if (Component.getInitialProps) {
// pageProps = await Component.getInitialProps(ctx);
// }
// return { pageProps };
// }
render() {
const { Component, pageProps, isAuthenticated } = this.props;
return (
<div>
<Layout isAuthenticated={isAuthenticated} {...pageProps}>
<Component {...pageProps} />
</Layout>
</div>
);
}
}
export default withData(MyApp);
layout.js
import React from "react";
import defaultPage from "../hoc/defaultPage";
class Layout extends React.Component {
constructor(props) {
super(props);
}
static async getInitialProps(ctx) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps, isAuthenticated };
}
render() {
const { isAuthenticated, children } = this.props;
return (
<div>
{isAuthenticated ? (
<h2>I am logged</h2>
) : (
<h2>I am not logged</h2>
)}
{children}
</div>
)
}
}
export default defaultPage(Layout);
defaultPage.js
/* hocs/defaultPage.js */
import React from "react";
import Router from "next/router";
import Auth from "../components/auth";
const auth = new Auth();
export default Page =>
class DefaultPage extends React.Component {
static async getInitialProps(ctx) {
const loggedUser = process.browser
? auth.getUserFromLocalCookie()
: auth.getUserFromServerCookie(ctx);
const pageProps = Page.getInitialProps && Page.getInitialProps(ctx);
let path = ""
return {
...pageProps,
loggedUser,
currentUrl: path,
isAuthenticated: !!loggedUser
};
}
render() {
return <Page {...this.props} />;
}
};
我在这里错过了什么?
【问题讨论】:
-
确保您已在 Apollo 中将获取策略更改为仅限网络。也许它正在尝试从缓存中读取。不久前我遇到了同样的问题。此外,您可能必须在登录后手动写入缓存。
标签: javascript reactjs oauth jwt next.js