如何在 Next.js 中访问 getServerSideProps 中的路由参数? [英] How to access route parameter inside getServerSideProps in Next.js?

查看:161
本文介绍了如何在 Next.js 中访问 getServerSideProps 中的路由参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 slug 中的 ID 查询我的 Supabase 表,例如localhost:3000/book/1 然后在 Next.js 的页面上显示有关该书的信息.

表格

book/[id].js

import { useRouter } from 'next/router'从@/utils/supbase-client"导入 { getBook };导出默认函数 Book({bookJson}) {常量路由器 = useRouter()常量 { id } = router.query返回 

<p>书:{id}</p><h1>{bookJson}</h1></div>}导出异步函数 getServerSideProps(query) {const id = 1//从 slug 获取 IDconst book = await getBook(id);const bookJson = JSON.stringify(book)返回 {道具: {图书Json}};}

utils/supbase-client.js

export const getBook = async (id) =>{常量 bookString = id让 bookId = parseInt(bookString);const { 数据,错误 } = 等待 supabase.from('书').select('id, name').eq('id', bookId)如果(错误){console.log(error.message);抛出错误;}返回数据 ||[];};

解决方案

getServerSideProps 文档,您可以通过 getServerSideProps 的上下文访问路由参数,使用 params字段.

<块引用>

params:如果该页面使用动态路由,params 包含路由参数.如果页面名称是 [id].js,那么 params 将类似于 { id: ... }.要了解更多信息,请查看动态路由文档.

导出异步函数 getServerSideProps(context) {const id = context.params.id//从 slug `/book/1` 获取 ID//`getServerSideProps` 代码的其余部分}

I want to query my Supabase table using the ID in the slug e.g. localhost:3000/book/1 then show information about that book on the page in Next.js.

Table

book/[id].js

import { useRouter } from 'next/router'
import { getBook } from '@/utils/supabase-client';

export default function Book({bookJson}) {
  const router = useRouter()
  const { id } = router.query
  
  return <div>
    <p>Book: {id}</p>
    <h1>{bookJson}</h1>
  </div>
}

export async function getServerSideProps(query) {
  const id = 1 // Get ID from slug
  const book = await getBook(id);
  const bookJson = JSON.stringify(book)

  return {
    props: {
      bookJson
    }
  };
}

utils/supabase-client.js

export const getBook = async (id) => {
  const bookString = id
  let bookId = parseInt(bookString);
  
  const { data, error } = await supabase
    .from('books')
    .select('id, name')
    .eq('id', bookId)

  if (error) {
    console.log(error.message);
    throw error;
  }

  return data || [];
};

解决方案

As described in getServerSideProps documentation, you can access the route parameters through the getServerSideProps's context, using the params field.

params: If this page uses a dynamic route, params contains the route parameters. If the page name is [id].js, then params will look like { id: ... }. To learn more, take a look at the Dynamic Routing documentation.

export async function getServerSideProps(context) {
    const id = context.params.id // Get ID from slug `/book/1`
    
    // Rest of `getServerSideProps` code
}

这篇关于如何在 Next.js 中访问 getServerSideProps 中的路由参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆