【问题标题】:Component does not receive props from getStaticProps when wrapped with HOC使用 HOC 包装时,组件不会从 getStaticProps 接收道具
【发布时间】:2021-06-07 20:44:37
【问题描述】:

谁能帮我解决关于下一个 SSR 和私有路由的技术问题? 我有一个使用 getStaticProps 的页面由 SSR 挂载,并希望保证只有授权用户才能访问。

我尝试了getServerSideProps,但我无法将getServerSidePropsgetStaticProps 一起使用。

我也尝试了一些 HOC 实现,但是当我的页面被 auth HOC 组件包装时,它不会执行 getStaticProps

编辑: 页面调用了getStaticProps,但没有收到getStaticProps 的更新数据。仅在道具上未定义。

我的getStaticProps

export const getStaticProps: GetStaticProps = async context => {
  const { slug } = context.params;

  const response = await api.get<ICourse>(`course/${slug}`);
  const course = response.data;
  return {
    props: {
      course,
    },
    revalidate: 600,
  };
};

export default privateRoute(Course);

我的 HOC

function redirectToHome() {
  router.replace('/');
}
function privateRoute(WrappedComponent: any) {
  return class extends Component<AuthProps> {
    state: { isLoading: boolean };

    constructor(props) {
      super(props);
      this.state = {
        isLoading: true,
      };
    }
    async componentDidMount(): Promise<void> {
      if (!cookies.get(AUTH_TOKEN_COOKIE)) {
        redirectToHome();
      }
      try {
        const user = await AuthService.getUser();
        if (user?._id) {
          const permit = await permissionService.get(user._id);
          if (!permit) {
            redirectToHome();
          }
        }
      } catch (e) {
        console.log(e);
        redirectToHome();
      }
    }

    render() {
      const { isLoading } = this.state;
      return (
        <div>{isLoading ? <>Check permission</> : <WrappedComponent />}</div>
      );
    }
  };
}
export default privateRoute;

【问题讨论】:

  • 你确定 getStaticProps 不会被 HOC 调用吗?你有任何错误吗?
  • 它被调用,但不要在页面上注入 staticprops。我的页面只收到未定义的道具。

标签: reactjs authentication next.js server-side-rendering higher-order-components


【解决方案1】:

您需要将道具从您的 HOC 传递到 &lt;WrappedComponent /&gt;

render() {
    const { isLoading } = this.state;
    return (
        <div>
            {isLoading ? <>Check permission</> : <WrappedComponent {...this.props} />}
        </div>
    );
}

【讨论】:

    猜你喜欢
    • 2023-01-22
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 2019-10-15
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多