使用getInitialProps将数据馈送到Next.js组件

When I talked about adding dynamic content to Next.js we had an issue with dynamically generating the post page, because the component required some data up front, and when we tried to get the data from the JSON file:

当我谈论向Next.js添加动态内容时,我们在动态生成帖子页面时遇到了一个问题,因为该组件需要预先提供一些数据,并且当我们尝试从JSON文件获取数据时:

import { useRouter } from 'next/router'
import posts from '../../posts.json'

export default () => {
  const router = useRouter()

  const post = posts[router.query.id]

  return (
    <>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </>
  )
}

we got this error:

我们收到此错误:

How do we solve this? And how do we make SSR work for dynamic routes?

我们该如何解决呢? 以及如何使SSR用于动态路由?

We must provide the component with props, using a special function called getInitialProps() which is attached to the component.

我们必须使用附加到组件的特殊函数getInitialProps()为组件提供道具。

To do so, first we name the component:

为此,首先我们将组件命名为:

const Post = () => {
  //...
}

export default Post

then we add the function to it:

然后我们添加功能:

const Post = () => {
  //...
}

Post.getInitialProps = () => {
  //...
}

export default Post

This function gets an object as its argument, which contains several properties. In particular, the thing we are interested into now is that we get the query object, the one we used previously to get the post id.

此函数将一个对象作为其参数,其中包含多个属性。 特别是,我们现在感兴趣的是获取query对象,这是我们先前用于获取帖子ID的对象。

So we can get it using the object destructuring syntax:

因此,我们可以使用对象分解语法来获取它:

Post.getInitialProps = ({ query }) => {
  //...
}

Now we can return the post from this function:

现在我们可以从该函数返回帖子:

Post.getInitialProps = ({ query }) => {
  return {
    post: posts[query.id]
  }
}

And we can also remove the import of useRouter, and we get the post from the props property passed to the Post component:

我们还可以删除useRouter的导入,然后从props属性中获取该帖子,并将其传递给Post组件:

import posts from '../../posts.json'

const Post = props => {
  return (
    <div>
      <h1>{props.post.title}</h1>
      <p>{props.post.content}</p>
    </div>
  )
}

Post.getInitialProps = ({ query }) => {
  return {
    post: posts[query.id]
  }
}

export default Post

Now there will be no error, and SSR will be working as expected, as you can see checking view source:

现在将没有任何错误,并且SSR将按预期运行,如您所见,检查视图源:

The getInitialProps function will be executed on the server side, but also on the client side, when we navigate to a new page using the Link component as we did.

当我们像以前一样使用Link组件导航到新页面时, getInitialProps函数将在服务器端和客户端执行。

It’s important to note that getInitialProps gets, in the context object it receives, in addition to the query object these other properties:

重要的是要注意,除了query对象之外, getInitialProps还从接收的上下文对象中获取以下其他属性:

  • pathname: the path section of URL

    pathname :URL的path部分

  • asPath - String of the actual path (including the query) shows in the browser

    asPath浏览器中显示的实际路径(包括查询)的字符串

which in the case of calling http://localhost:3000/blog/test will respectively result to:

在调用http://localhost:3000/blog/test将分别导致:

  • /blog/[id]

    /blog/[id]

  • /blog/test

    /blog/test

And in the case of server side rendering, it will also receive:

对于服务器端渲染,它还将收到:

  • req: the HTTP request object

    req :HTTP请求对象

  • res: the HTTP response object

    res :HTTP响应对象

  • err: an error object

    err :错误对象

req and res will be familiar to you if you’ve done any Node.js coding.

如果您已完成任何Node.js编码,那么reqres将会为您所熟悉。

翻译自: https://flaviocopes.com/nextjs-getinitialprops/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值