在还包含getInitialProps的HOC中使用getInitialProps

reactjs React.js

老丝蛋蛋

2020-03-23

我用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);

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;
};

第2950篇《在还包含getInitialProps的HOC中使用getInitialProps》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
神乐古一 2020.03.23

Try calling C.getInitialProps() inside the getInitialProps of your HOC:

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;
};

I hope this helps.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android