在nextjs的Layout组件中使用getInitialProps

时间:2019-04-11 07:24:57

标签: javascript reactjs next next.js

因此,我在layouts文件夹中拥有此布局组件,在其中无法访问getInitialProps。我想做的是在布局组件中使用getInitialProps。我已经读过一些文章,需要将布局组件放在_app.js文件中,我不希望所有页面都访问该布局。

import React, {Component, Fragment} from 'react'
import PropTypes from 'prop-types'

class WithUserLayout extends Component {
  static async getInitialProps() {
    console.log('layout')
  }
  render() {
    const {children} = this.props
    return (
      <Fragment>
        {children}
      </Fragment>
    )
  }
}

WithUserLayout.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node
  ])
}
export default WithUserLayout

有办法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

实际上我的评论不好。是的,HOC是解决此问题的好方法。 getInitialProps仅可用于页面组件,条件是该组件外部没有包装HOC。现在您有了一个HOC,getInitialProps就可以使用了,但现在还没有实际的页面组件!因此,您必须从此HOC手动调用该方法,如下所示:

import React, {Component, Fragment} from 'react'
import PropTypes from 'prop-types'

const withUserLayout = (child: Child) => {
  return class WithUserLayout extends Component {
    static async getInitialProps(ctx) {
      let pageProps = {};
      try {
        if (Child.getInitialProps) {
          pageProps = await Child.getInitialProps(ctx);
        } 
      } catch (err) {
       throw new Error(`Cannot invoke getInitalProps of ${Child.displayName}`, err.stack);
      }

      return pageProps;
    }

    render() {
      // Rendering
    }
  }
}

有关更多信息,请查看此useful code snippet

相关问题