简体   繁体   中英

How do I pass a custom parameter to nextjs dynamic route so I can access it inside getInitialProps

I want to pass an ID as a custom parameter to next/link <Link /> and be able to access it inside getInitialProps. I want to use clean URL's but the API i'm using only allows you to query it via the post ID. So while I can access the post slug inside getInitialProps I cant use it to query the post.

I currently have it set up to use the post slug in the URL

<Link href="/article" as={`/article/${urlPattern}`}>
    <a>{title}</a>
</Link>

and in getInitialProps I can access the slug via the context parameter

Article.getInitialProps = async context => {
    const slug = context.query;
    // need query ID
    // do api call
};

Is there a way I can pass the ID to so I can access it inside getInitialProps via the context to do my API call?

** EDIT **

I've updated the by adding a query property which allows me to access the id via context.query.id but doing so also updates the page URL to /article/the-article-title?id=234234324324 I dont want the URL to include the article id just the article name but I still need a way to access the article ID inside getInItialProps so I do the api call.

<Link
    href="/article/[article]"
    as={{
        pathname: `/article/${urlPattern}`,
        query: { id: system.id }
    }}
>

You could pass an URL object to the as prop:

<Link
      href={"/article"}
      as={{
        pathname: "/article",
        query: { id: "query id" }
      }}
    >
      <a>title</a>
    </Link>

There is an example: https://github.com/zeit/next.js/tree/master/examples/with-url-object-routing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM