如何将HOC道具传递给getInitialProps?

时间:2019-10-11 15:24:18

标签: javascript reactjs next.js

_app.js中,我将MyApp包裹在可获取用户状态的HOC(高阶订单组件)中。

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;

如何在isAuthenticated中提取Page.getInitialProps

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

1 个答案:

答案 0 :(得分:1)

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

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

相关问题