getInitialProps 永远不会执行

getInitialProps is never executed

我正在尝试制作一个 Twitter 组件,从推特 API 加载推文并显示其 HTML,这将是一个 <blockquote> 和一个 <script> 标签。

这样做的好处是,如果服务器端呈现,即使用户的隐私设置阻止了对 Twitter 脚本的调用,它也能正常工作:用户仍然会得到 blockquote,这比当前的要好行为(什么都不显示)。

所以,我的想法是做这样的事情:

import fetch from 'node-fetch'

function Tweet(props) {
  return <>
    <div dangerouslySetInnerHTML={{
      __html: props.__html
    }} />
    <p>here I am</p>
  </>
}

Tweet.getInitialProps = async ctx => {
  console.log("here I am on the road again")
  const res = await fetch(`https://api.twitter.com/1/statuses/oembed.json?id=${ctx.tweetId}`)
  const json = await res.json()
  return { __html: json.html }
}

export default Tweet

然后在页面上像 <Tweet tweetId="blah" /> 一样使用它。

不过我发现我的想法有两个问题:

  1. 根据文档,我无法在 getInitialProps
  2. 上访问 tweetId 属性
  3. getInitialProps 永远不会被调用。 <p>here I am</p> 出现在 HTML 上,日志永远不会打印在任何地方。

所以,我的问题是:我做错了什么?这甚至可以做到吗?

谢谢!

根据Next.js documentationgetInitialProps只能用于页面,不能用于组件:

getInitialProps can only be added to the default component exported by a page, adding it to any other component won't work.