【问题标题】:How to link same page with two urls in nextjs如何在 nextjs 中将同一页面与两个 url 链接
【发布时间】:2021-05-06 08:54:50
【问题描述】:

如果用户正在搜索特定城市,我想在页面名称之前的 url 中显示城市名称,如果用户不是在搜索特定城市,那么我想显示普通 url。我们如何在 Next Js 中实现这一点。

例如

     http://localhost:3000/Delhi/furniture
     http://localhost:3000/furniture

两个网址都应该指向同一个页面。

我尝试了下一个/链接组件。

<Link href='/furniture' as={config.city ? config.city + '/furniture': 'furniture'}><a>Furniture</a></Link>

Link 有两个 props href 和 as。使用 as 我们可以显示与实际 url 不同的 url,但如果您直接点击由 'as' 属性更改的 url,它将显示 404 页面未找到。我找不到任何可以实现上述目标的端口或功能。

【问题讨论】:

  • 我认为您至少应该在其中一个路由上渲染页面,并从另一个路由重定向到该路由,或者在两个路由上渲染相同的组件。你已经尝试过什么?你能提供一个Minimal, Complete, and Reproducible Code Example吗?

标签: reactjs next.js server-side-rendering


【解决方案1】:

您可以在next.config.js 中使用rewrites 将包含城市的路径映射到furniture 路径。

// next.config.js

module.exports = {
    async rewrites() {
        return [
            {
                source: '/:city/furniture',
                destination: '/furniture'
            }
        ];
    }
}

您还可以添加regex path matching 以允许仅匹配:city 的某些值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2012-03-20
    • 1970-01-01
    • 2017-09-20
    相关资源
    最近更新 更多