【问题标题】:How can I use one component (page) for multiple route in Next JS如何在 Next JS 中将一个组件(页面)用于多个路由
【发布时间】:2022-02-10 20:07:37
【问题描述】:

众所周知,Next JS 没有任何路由,我正在尝试在 next JS 中构建一个 Web 应用程序,在该应用程序中,我必须对多个路由使用相同的组件,而无需复制粘贴到不同的目录。

目录结构:

src
    pages
        new (AddListComponent)
        edit-[id] (AddListComponent)

添加列表组件

import React from 'react'
import { withRouter } from 'next/router'

class Listing extends React.Component {
    constructor(props){
        super(props)
        this.state = {
        }
    }
    render () {
        return (
            <div>This is my new component</div>
        )
    }
}
export default withRouter(Listing)

【问题讨论】:

标签: javascript reactjs next.js


【解决方案1】:

在路由目录中,您可以从另一个目录导入和导出组件。

在您的第二条路线 /myPage2/index.js 内:

import MyPage from ../myPage.js
export default MyPage

【讨论】:

  • 我想知道当我们有动态路线时该怎么做
【解决方案2】:

您可以使用可选参数创建页面。

pages
 ┣ tasks
 ┃ ┣ manage
 ┃ ┃ ┗ [[...id]].jsx
 ┃ ┣ index.jsx
 ┃ ┗ service.js
 ┣ _app.jsx
 ┣ dashboard.jsx
 ┣ index.jsx
 ┗ login.jsx

/tasks/managetasks/manage/14 将路由相同的组件 [[...id]].jsx

  • 不要忘记使用双括号和三个点。 [[...foo]].jsx

可以通过在 双括号([[...slug]])。

例如 pages/post/[[...slug]].js 会匹配 /post, /post/a, /post/a/b 等等。

check了解更多信息。

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 2020-11-21
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    相关资源
    最近更新 更多