如何使用 "useRouter" 在 Next.js 中的 getServerSideProps() 中获取 url 中的参数

How can I use "useRouter" to get params in the url inside getServerSideProps() in Next.js

我想在 getServerSideProps() 函数中获取 URL 参数。这是我的代码。

我的代码的目的是从 URL 获取参数并获取 API 并在前端显示输出。

import { useRouter } from 'next/router'
import connectMongo from '../../utils/connectMongoos';
import Post from '../../models/postModel';
import MarkdownComponent from '../../components/utils/markdown';

export const getServerSideProps = async () => {
  try {
    console.log('CONNECTING TO MONGO');
    await connectMongo();
    console.log('CONNECTED TO MONGO');

    console.log('FETCHING DOCUMENTS');
    // find the post with the slug that matches the slug in the url
    const post = await Post.findOne({ slug: router.query.slug }); // error comes here
    console.log('FETCHED DOCUMENTS');

    return {
      props: {
        data: JSON.parse(JSON.stringify(post)),
      },
    };
  } catch (error) {
    console.log(error);
    return {
      notFound: true,
    };
  }
};

export default function Posts({data}) {
  const router = useRouter()
  // const { slug } = router.query
  return(
    <div className="max-w-screen-md mx-auto font-inter m-2 p-4">
      <MarkdownComponent text={data.markdown} />
    </div>
  )
}

这是我遇到的错误,

ReferenceError: router is not defined
    at getServerSideProps (webpack-internal:///./pages/post/[slug].js:26:19)
    at runMicrotasks (<anonymous>)

根据 NextJs getServerSideProps Documentation,您可以使用 params 字段通过 getServerSideProps 的上下文访问路由参数。

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: ... }.

query: An object representing the query string.


     export async function getServerSideProps(context) {
        const slug = context.params // `Get the router query or slug here`
        
        // Rest of `getServerSideProps` code
    }