如何访问 Next.js 中 getServerSideProps 中的路由参数?

Tom*_*cks 36 javascript next.js supabase

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

桌子

在此输入图像描述

书/[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
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

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 || [];
};
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 58

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

\n
\n

params:如果该页面使用动态路由params则包含路由参数。如果页面名称是[id].js,那么params将会是这样的{ id: ... }

\n

\xe2\x80\x94 Next.js,数据获取:getServerSideProps,Context 参数

\n
\n
export async function getServerSideProps(context) {\n    const id = context.params.id // Get ID from slug `/book/1`\n    \n    // Rest of `getServerSideProps` code\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

或者,您也可以使用该query字段来访问路由参数。不同之处在于,它query还将包含 URL 中传递的任何查询参数。

\n
export async function getServerSideProps(context) {\n    const id = context.query.id // Get ID from slug `/book/1`\n    // If routing to `/book/1?name=some-book`\n    console.log(context.query) // Outputs: `{ id: \'1\', name: \'some-book\' }`\n\n    // ...\n}\n
Run Code Online (Sandbox Code Playgroud)\n

  • `context.query.accountId` 是我所需要的(从根据 https://nextjs.org/docs/routing/dynamic-routes 定义的 slug 中提取)。谢谢。 (3认同)