如何将 HOC props 传递给 getInitialProps?
How to pass HOC props to getInitialProps?
在 _app.js
中,我用获取用户状态的 HOC(高阶组件)包装了我的 MyApp
。
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
更合适。
无法从静态方法访问实例属性。
参见:
尽管它是打字稿,但适用相同的规则。
在 _app.js
中,我用获取用户状态的 HOC(高阶组件)包装了我的 MyApp
。
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
更合适。
无法从静态方法访问实例属性。
参见:
尽管它是打字稿,但适用相同的规则。