【问题标题】:How to pass additional parameter with dynamic routes in Reactjs如何在 Reactjs 中使用动态路由传递附加参数
【发布时间】:2023-01-18 23:54:30
【问题描述】:

我在 Reactjs 中工作并使用 nextjs,我的 [slug.js] 可以正常使用以下 url

<Link href={`/${post.slug}`}><a>

但是我想用这个发送/传递“隐藏”(附加参数),每当我尝试这样做时我都会收到 404 错误,我想要这个是因为在某些页面中我想在“serversideprops”中使用不同的 api,现在在这里是我的代码

export const getServerSideProps = async ({ params }) => {
    console.log(params); // right now i am getting "slug" as parameter
    if(params.anotherparamter)
    {
        //futher code
    }
    elseif(params.slug){    
        const { data: data2 } = await Axios.get(`https://xxxxxxxxxxxxxxxxxxxxxxxxx/${params.slug}`);
    }
    const blogs = data2;
    return {
        props: {
           blogs: blogs
        },
    };
};

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    您可以使用 as 属性来隐藏查询字符串。

    您的链接看起来像这样

    <Link href={`/${post.slug}?myparam="mysecret"`} as={`/${post.slug}`}></Link> //The link will not show the query param when redirected 
    

    然后,您将能够像这样访问 serverSideProps 中的 myparam 查询。

    export const getServerSideProps = async ({ params, query }) => {
    ...
    const { myparam } = query
    console.log(myparam) // will return mysecret as a string
    

    您可以从文档中阅读更多内容

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-04
      • 2022-10-18
      • 2019-08-22
      • 2022-01-23
      相关资源
      最近更新 更多