next.js将道具从HOC传递到子组件getInitialProps

我想在我的应用程序中为页面创建一个HOC,以提供一些信息,这些信息存储在本地存储中,以防页面未在服务器上呈现。

我只能从中实际设置数据,componentDidMount因为我需要访问localStorage(显然在Node env中不可用)。

import * as React from 'react'
const withLogin = Page => class SecurePage extends React.Component {
  static async getInitialProps (ctx) {

    let language;
    if (ctx.req) {
        language = ctx.req.session.language;
    } else {
        language = localStorage.getItem('language');
    }

    let props = {}
    if (Page.getInitialProps) {
        const pageProps = await Page.getInitialProps(ctx);
        props = { ...pageProps, language }
    }

    console.log("this is what the props look like in the wrapping component", props)

    return props;

    // return Page.getInitialProps && { ...(await Page.getInitialProps(ctx)), language }
  }

  componentDidMount () {
      const { language } = this.props;
      if (language) {
          /* if we were able to fetch the language, set it here */
          localStorage.setItem('language', language);
      }
  }

  render () {
      console.log("pre-render page props ", this.props);
    return <Page {...this.props} /> 
  }
}

export default withLogin

当我为它配备组件时,HOC getInitialProps函数将按预期运行,但它对呈现的组件的getInitialProps函数没有影响。我没有办法通过HOC模式将prop传递给子组件的getInitialProps吗?

class EmployerJobList extends React.Component {
    static async getInitialProps(props) {

        if (props.req) {
            /* SSR */
            // language = req.session.language;
        } else {
            /* non-SSR */
            // language = user.preferred_language;
        }
        console.log("got language", props.language); // => undefined
        getUrl (`/api/localization?filename=create-job&language=${props.language}`)
        .then( jsonRes => {
            console.log(jsonRes);
        })
        ...
     export default withLogin(EmployerJobList)

如果这不是可行的模式;我有什么可靠的方法可以与localStorage共享/重用我想要的逻辑吗?

从理论上讲,我可以在每个Page组件中执行此操作:

static async getInitialProps(props) {

    let language;
    if (props.req) {
        /* SSR */
        language = req.session.language;
    } else {
        /* non-SSR */
        language = localStorage.getItem('language') // works
    }
    ...

但这似乎是多余的。