簡體   English   中英

在 nextjs 的 Layout 組件中使用 getInitialProps

[英]Use getInitialProps in Layout component in nextjs

因此,我將此布局組件位於無法訪問 getInitialProps 的layouts文件夾中。 我想要做的是在我的布局組件中使用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

有沒有辦法做到這一點?

謝謝!

其實我的評論不好。 是的,HOC 是解決這個問題的好方法。 getInitialProps僅可用於頁面組件, 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
    }
  }
}

如需進一步參考,請查看此有用的代碼片段

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM