无法访问从getInitialProps传递的变量

时间:2020-02-16 15:10:05

标签: next.js

我有一个问题,我无法访问getInitialProps中定义的变量。 所以有一个简单的页面

class DoctorsPage extends React.Component {
  static async getInitialProps(ctx) {
    return { stars: 23526 }
  }
  render() {
    // this.props.stars is undefinde
    return <div>Next stars: {this.props.stars}</div>
  }
}
export default DoctorsPage

即使我以文档中的示例为例。 stars未定义。

import fetch from 'isomorphic-unfetch'

function HomePage({ stars }) {
  return <div>Next stars: {stars}</div>
}

HomePage.getInitialProps = async () => {
  const res = await fetch('https://api.github.com/repos/zeit/next.js')
  const json = await res.json()
  console.log(json)
  return { stars: json.stargazers_count }
}

导出默认主页

文件路径很好,应该是/pages/[city]/doctors/[specialization]/[page]/index.js app.js

class MyApp extends App {
  static async getInitialProps({Component, ctx}) {
    let pageProps = {}
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }
    return {
      ...pageProps,
    }
  }
  render() {
    const {
      Component,
      pageProps,
      router,
      store
    } = this.props
    ....
    return (
      <IntlProvider locale={locale} messages={messages} defaultLocale={fallbackLanguage}>
        <RSIntlProvider locale={ruRU}>
          <Provider store={store}>
            <Page router={router}>
              <Component {...pageProps} />
            </Page>
          </Provider>
        </RSIntlProvider>
      </IntlProvider>
    )
  }
}
export default withRedux(createStore)(withReduxSaga(MyApp))

也许_document.js也会有所帮助?

import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage
    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
        })
      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }
}

我在做什么错?可能是Page组件出现问题还是如此?谢谢!

0 个答案:

没有答案