【问题标题】:How to pass HOC props to getInitialProps?如何将 HOC 道具传递给 getInitialProps?
【发布时间】:2019-10-11 23:48:39
【问题描述】:

_app.js 中,我将MyApp 包裹在一个获取用户状态的HOC(Higer Order Component)中。

import AuthHoC from '../utils';
import App from 'next/app';

class MyApp extends App {
  render() {
    const { Component, pageProps, isAuthenticated, idToken } = this.props;

    return (
      <Component 
        {...pageProps} 
        isAuth={isAuthenticated} // Given by AuthHOC
        idToken={idToken}        // Given by AuthHOC
      />
    );
  }
}

export default AuthHoC(MyApp); 

在我的页面中,我想通过getInitialProps 获取状态。

class Page extends React.Component {
    ...
    render() {
        return (
            <Layout>...</Layout>
        );
    }
}

Page.getInitialProps = async (ctx) => {
    console.log('How can I access this -> isAuthenticated'); 
    // if user is not auth, redirect or pass.
    return {}
};

export default Page;

如何在Page.getInitialProps 中获取isAuthenticated

当然,我可以使用ComponentDidMount() 根据用户的状态进行重定向,但是加载时间稍长,他们可以在Router.push('/') 触发之前看到页面。这就是为什么我认为改用getInitialProps 会更合适。

【问题讨论】:

  • 为什么getInitialProps不在课堂内?
  • @JosephD。它也可以在里面使用static async getInitialProps(ctx) {...},在这个问题上没有太大的改变,我只是为了可读性把它分开了。
  • 如何在静态方法中访问this
  • @DhananjaiPai 我知道我不能,我正在寻找访问isAuthenticated 的方法。这就是我打开这篇文章的原因。
  • @JosephD。这就是我想知道的,为了访问ctx,我需要以某种方式定义它。

标签: javascript reactjs next.js


【解决方案1】:

无法从静态方法访问实例属性。 见:How to access non static property from static function in typescript

尽管它是打字稿,但适用相同的规则。

【讨论】:

  • 如果你说的是对的,那么我唯一的选择就是使用cookies对吗?
  • 您当前的身份验证策略是什么?我的意思是,看起来您的 HOC 已经在传递 isAuthenticated,因此您可能会记住您的组件并通过上下文传递 isAuthenticated 以在您的子应用程序中访问它。
  • 这就是我的想法,如果我将它保存在 cookie 或本地存储中,我可以通过上下文访问它。​​
  • 经过一番思考,我不需要重定向,我可以简单地将一个道具传递给Layout,并在那里显示一条禁止消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2021-05-05
  • 2020-04-28
  • 2022-01-10
  • 2019-08-12
  • 1970-01-01
相关资源
最近更新 更多