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

时间:2019-01-16 05:05:57

标签: javascript reactjs next.js

我想为我的应用程序中的页面创建一个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模式将道具传递给子组件的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
    }
    ...

但这似乎不必要地多余。

1 个答案:

答案 0 :(得分:1)

通过将值作为参数提供,可以将值传递到孩子的#include "3rdParty/crash-report.h" int main(int argc, char *argv[]) { CrashReporter crashReporter; (void)crashReporter; //prevents unused warnings // [application main loop should be here] return 0; } 函数中:

getInitialProps

然后在子组件的getInitialProps中,我可以访问新参数:

  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, language); // <--- this
        props = { ...pageProps, language }
    }
    return props;
  }