【问题标题】:getStaticProps in HOC not working in Next.jsHOC 中的 getStaticProps 在 Next.js 中不起作用
【发布时间】:2021-02-25 15:23:34
【问题描述】:

我有一个 HOC 和一个用于该 HOC 的 getStaticProps 函数,如下所示:

const WrappedPage = () => {
    const WithLocale = ({ locale, ...pageProps }) => {
        if (!locale) {
            return <Error statusCode={404} />
        }
        return (
            <LocaleProvider lang={locale}>
                <WrappedPage {...pageProps} />
            </LocaleProvider>
        )
    }

    return WithLocale
}

export default WrappedPage

export const getStaticProps = async ctx => {
    let pageProps = {}
    if (WrappedPage.getStaticProps) {
        pageProps = await WrappedPage.getStaticProps(ctx)
    }
    if (typeof ctx.query.lang !== 'string' || !isLocale(ctx.query.lang)) {
        return { ...pageProps, locale: undefined }
    }
    return { ...pageProps, locale: ctx.query.lang }
}

由于某种原因,此处 HOC 的 getStaticProps 函数不起作用。如果我尝试在函数内控制台记录ctx,它不会输出任何内容。

任何关于我在这里做错的指针将不胜感激。

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    我不确定您是否以正确的方式使用 HOC,参考 (https://reactjs.org/docs/higher-order-components.html)

    在 HOC 中,你传入一个组件,HOC 会提供额外的 props 和/或渲染组件:

    const WithLocale = (Component, locale, ...otherProps) => {
        if (!locale) {
            return <Error statusCode={404} />
        }
        return (
            <LocaleProvider lang={locale}>
                <Component {...otherProps} />
            </LocaleProvider>
        )
    }
    
    const WrappedPage = ({prop1, prop2}) => <h1>{prop1 + ' ' + prop2}</h1>
    
    export default withLocale(WrappedPage, locale, prop1, prop2 etc)
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2021-03-17
      • 2023-01-04
      • 1970-01-01
      • 2020-10-29
      • 2023-04-03
      • 2021-12-03
      • 2021-06-06
      • 2020-12-18
      相关资源
      最近更新 更多