我用 withAuth HOC 包装了一个页面。在同一页面中,我还尝试调用 getInitialProps。如果我登录,getInitialProps 函数不会运行(尽管它表明我的 withAuth HOC 正在工作)。
无论如何,我可以使联系人页面的 getInitialProps 工作并使用 withAuth HOC(它也有一个 getInitialProps 函数)?
接触
import Layout from "../components/Layout";
import { withAuth } from "../services/withAuth";
class Contact extends React.Component {
static async getInitialProps(ctx) {
console.log("@contact authenticated ", ctx);
return {};
}
render() {
return (
<Layout>
<p>hey there</p>
<a href="mailto:abc@gmail.com">abc@gmail.com</a>
</Layout>
);
}
}
export default withAuth(Contact);
Run Code Online (Sandbox Code Playgroud)
withAuth HOC
import { ME } from "../graphql/queries";
import redirect from "../lib/redirect";
export const withAuth = C => {
class AuthComponent extends React.Component {
static async getInitialProps(ctx) {
const response = await ctx.apolloClient.query({ query: ME });
console.log("@withAuth ", response);
if (!response || !response.data || !response.data.me) {
redirect(ctx, "/");
return {
me: null
};
}
return {
me: response.data.me
};
}
render() {
return <C {...this.props} />;
}
}
return AuthComponent;
};
Run Code Online (Sandbox Code Playgroud)
尝试C.getInitialProps()在HOC的getInitialProps中调用:
export const withAuth = C => {
class AuthComponent extends React.Component {
static async getInitialProps(ctx) {
const response = await ctx.apolloClient.query({ query: ME });
console.log("@withAuth ", response);
if (!response || !response.data || !response.data.me) {
redirect(ctx, "/");
return {
me: null
};
}
// Get component’s props
let componentProps = {}
if (C.getInitialProps) {
componentProps = await C.getInitialProps(ctx);
}
return {
me: response.data.me,
...componentProps
};
}
render() {
return <C {...this.props} />;
}
}
return AuthComponent;
};
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
4187 次 |
| 最近记录: |