gpt4 book ai didi

javascript - 如何将 HOC props 传递给 getInitialProps?

转载 作者:行者123 更新时间:2023-11-29 22:46:29 25 4
gpt4 key购买 nike

_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 更合适。

最佳答案

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

尽管它是 typescript ,但适用相同的规则。

关于javascript - 如何将 HOC props 传递给 getInitialProps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58344313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com