使用带有 Next JS 路由的 React 路由器 [英] using React router with Next JS route
问题描述
我有一个简单的问题,我是 Next.JS 的新手我们有一个项目,我的 Web 应用程序使用 Next JS 在后端管理路由
i have simple question , i am new in Next.JS we have a project and my web application manage routes in BackEnd with Next JS
现在我的问题来了,我想在一个部分使用 React-Router-dom
now my problem is here , i want use React-Router-dom in one section
例如在我使用 Laravel 和 React 之前
forexample before im working with Laravel and React
在 Laravel 中我这样设置我的路线
in Laravel I set My Route like This
Route::get('/reactPage/*' ...)
然后使用带有 react 的客户端路由
and then use Clien route with react
但我不知道如何用 Next JS 处理这个问题
but i dont know how handle this with Next JS
(更多详细信息=>例如,我希望用户在该用户看到其中包含某些链接的页面后单击某个链接,如果用户单击该链接,则 react-router-dom 处理路由并且没有任何请求发送到服务器)
( more details => for example i want user click to some link after that user see a page with some link inside of them , if user click that link , react-router-dom handle route and no any request send to Server )
推荐答案
我会推荐使用 Next 路由器.您确实需要创建一个自定义服务器以重载默认的 Next 路由,但这是一项微不足道的任务:
I would recommend using the Next router. You do need to create a custom server in order to overload the default Next routing, but its a trivial task:
// server.js
const { createServer } = require('http');
const next = require('next');
const routes = require('./routes');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = routes.getRequestHandler(app);
app.prepare().then(() => {
createServer(handler).listen(port, err => {
if (err) {
throw err;
}
console.log(`> Ready on http://localhost:${port}`);
});
});
然后你就可以定义路由了,我在 routes.js 文件里做的:
Then you can define routes, which I do in the routes.js file:
// routes.js
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());
routes
.add('landing', '/')
.add('profile', '/profile', 'profile');
这篇关于使用带有 Next JS 路由的 React 路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!