reactjs - 将 getInitialProps 与 HOC 一起使用,其中也包含 getInitialProps

标签 reactjs next.js

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

最佳答案

尝试在 HOC 的 getInitialProps 内调用 C.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;
};

我希望这会有所帮助。

关于reactjs - 将 getInitialProps 与 HOC 一起使用,其中也包含 getInitialProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55869475/

相关文章:

javascript - 选项卡打开时持续的 session 的身份验证逻辑

javascript - 无法使用 react-starter-kit 重新渲染组件

css - next.js 使用现在缺少的样式部署,styles.css 404 响应

javascript - 使用 next-redux-wrapper 访问 React 外部的 Redux store

reactjs - 使用 NextJS 和 next-routes,如何处理来自 server.js 和客户端的 404

javascript - 单击按钮不会在第一次单击时更新 this.setState;第二次点击更新

Javascript/React - 获取数组中匹配特定条件的第一项

reactjs - 无法读取未定义的属性 'subscribe'-Redux Persist

reactjs - 使用 React Query 更新缓存后是否可以重新渲染组件?

azure - Next.js 中的公共(public)环境变量在 Azure 静态 Web 应用程序中不起作用