【问题标题】:Pass data to getServerSideProps from previous page in NextJS将数据从 NextJS 中的上一页传递给 getServerSideProps
【发布时间】:2020-08-09 06:50:06
【问题描述】:

我正在使用 NextJS 开发一个类似电子商务的网站。

我将在/products 页面中获取并显示产品列表。在点击任何产品时,我将导航到 /details/[productId],然后我将获取这些产品详细信息,如下所示。

// In /details/[productId].js file

export async function getServerSideProps({params}) {
    const res = await fetch(`https:my-api-url/api/products/${params.productId}`)
    const product = await res.json()
    return {
        props: {
            product
        }
    }
}

问题

在这一步之前一切看起来都很好。但我想减少数据库读取次数,因此我计划使用在上一页 (/products) 中获取的数据,而不是在 detail 页面中再次获取产品详细信息,其中将包含有关产品的信息。因此,我需要一种方法将这些产品对象传递到下一个屏幕/details/[productId] 的 getServerSideProps(以实现 SSR 以用于 SEO)。

解决方法

我目前拥有的一个解决方案是 stringify 产品 json 并通过查询参数传递它并在 getServerSideProps({params, query}) 中取回它。但它只是在浏览器中向我的 url 发送垃圾邮件,看起来一点也不好看。

期待

有没有其他方法可以将数据传递给getServerSideProps 函数,以便它利用数据在服务器本身生成整个页面。请指导我克服这个问题。任何帮助,将不胜感激。

提前致谢.. (:

【问题讨论】:

  • 如果您找到了此查询的答案,请发布。即使我被这个问题所困扰。
  • @Karthik 还没有兄弟,目前我在每个页面中都点击了两次服务。给问题投票,这样任何人都会注意到这个问题。
  • 但是这种方法似乎有缺陷,因为当有人直接获取您的 /page/[pageId] 的链接时,不会有任何数据从某处传递,但是。注意:如果我弄错了,请告诉我,因为我刚开始使用 nextjs,我不知道它是如何工作的
  • 而且我认为您将使用可以在服务器上轻松生成的数据重载请求对象。加上在某些情况下发送一些敏感信息将是一个问题

标签: next.js server-side-rendering


【解决方案1】:

您可以以 express 方式引入自定义服务器,该服务器在您的应用程序或请求的整个生命周期内提供 locals 属性。

const next = require('next');
const express = require('express');

const app = next({ dev: process.env.NODE_ENV !== 'production' });
const handle = routes.getRequestHandler(app);
const env = process.env.NODE_ENV || 'dev';


app.prepare().then(() => {
  const server = express();
   
  server.get('/products', async (req, reply) => {
    const products = await //... fetch product with details
    req.app.locals.products =  products;
    return app.render(req, reply, '/path/to/products/page', req.query);
  });
  
  server.get('/details/:productId', async (req, reply) => {
    const {productId} = req.params;
    const {products} = req.app.locals;
    // find product using productId and make available in req.locals
    req.locals.product = // product;
    return app.render(req, reply, '/path/to/product/detail/page', req.query)
  }); 
  
  server.get('*', (req, reply) => {
    return handle(req, reply)
  });

  server.listen(3000);
});

请注意您的产品列表会增长到多大,以避免您的应用程序内存不足。

您还可以在产品请求 (See limits for HTTP cookies) 中返回包含产品列表的 cookie。然后在产品详细信息页面上阅读。

【讨论】:

    【解决方案2】:

    当我输入 URL http://localhost:3000/blog/wfe436

    //getting the meta tags dynamically
    
    export const getServerSideProps = async ({ params }) => {
        // Get external data from the file system, API, DB, etc.
        console.log(params) // here is the data of the url { blogname: 'wfe436' }
        const posts = Data
        // The value of the `props` key will be
        //  passed to the `Home` component
        return {
            props: { posts }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-25
      • 2021-05-13
      • 2021-03-18
      • 2021-04-20
      • 1970-01-01
      • 2021-10-06
      • 2021-07-15
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多