【问题标题】:NextJS different page name from url nameNextJS 与 url 名称不同的页面名称
【发布时间】:2020-12-19 06:54:30
【问题描述】:
我在 NextJS 中做一个项目,但是我发现我的 pages 文件夹中的文件名表示 URL 栏中显示的路径。
有什么办法可以让我拥有这样的结构:
- Pages
- 1.jsx
- 2.jsx
- 3.jsx
然后将其渲染到 url 或路径:http://localhost:3000/about 其中3.jsx 将映射到 about 链接?
【问题讨论】:
标签:
javascript
node.js
reactjs
next.js
【解决方案1】:
在 next.js 中创建自定义服务器
关注this 官方文档。您可以管理代码中的每条路线。
// server.js
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
if (pathname === '/about') {
app.render(req, res, '/3', query) // Pass the file name here so that it reads the proper file from /pages directory
} else {
handle(req, res, parsedUrl)
}
}).listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
其他例子在这里:-
【解决方案2】:
您可以将页面内容分隔在不同的文件夹中(不映射/3),默认导出到about.jsx。
// someFolder/3.jsx
export function AboutPage(){
return <div>about</div>
}
// pages/about.jsx
import { AboutPage } from '../somefolder/3.jsx'
export default AboutPage
我一直在使用这种结构来执行领域驱动开发、关注点分离以及更清晰地键入道具。唯一的问题是同时可视化静态道具和客户端获取有些困难。