簡體   English   中英

將數據從 NextJS 中的上一頁傳遞給 getServerSideProps

[英]Pass data to getServerSideProps from previous page in NextJS

我正在使用 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頁面中再次獲取產品詳細信息,其中將包含有關產品的信息。 因此,我需要一種方法將這些產品 object 傳遞到下一個屏幕/details/[productId]的 getServerSideProps (以實現用於 SEO 的 SSR)。

解決方法

我目前擁有的一種解決方案是將產品 json stringify並通過查詢參數將其傳遞並在getServerSideProps({params, query})中取回。 但它只是在瀏覽器中向我的 url 發送垃圾郵件,看起來一點也不好看。

期待

有沒有其他方法可以將數據傳遞到getServerSideProps function 以便它利用數據在服務器本身中生成整個頁面。 請指導我克服這個問題。 任何幫助,將不勝感激。

提前致謝.. (:

您可以將自定義服務器作為 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);
});

請注意您的產品列表增長到多大,以避免在 memory 之外運行您的應用程序。

您還可以在產品請求中返回包含產品列表的 cookie(請參閱 HTTP cookies 的限制)。 然后在產品詳細信息頁面上閱讀。

當我輸入 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 }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM