我能想到的解决方案是添加一个custom server,在其中解析/pathname/some-sub-information之类的路径并将其转换为页面以呈现pathname和一些额外的参数some-sub-information
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) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl; // pathname = '/pathname/some-sub-information'
const parts = pathname.split('/');
const page = parts[1]; // 'pathname'
const param = parts[2]; // 'some-sub-information'
if (page) {
const queryParams = { ...query, pageParam: param };
app.render(req, res, '/' + page, queryParams);
} else {
handle(req, res, parsedUrl);
}
}).listen(3000, err => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});
从服务器传递到客户端 app.render(req, res, '/' + page, { pageParam: 'test' }); 的参数可以在 getInitialProps query 参数中访问,例如query.pageParam
所以页面看起来像这样
pages/index.js
function Index({ pageParam }) {
return (
<div>
INDEX component with {pageParam}
</div>
);
}
Index.getInitialProps = async ({ query }) => {
const { pageParam } = query;
return { pageParam };
};
export default Index;
拥有这个自定义服务器和pages/index.js (node server.js),转到/index/some-data-here 将导致following page
希望对您有所帮助!