[英]React-router subdomain routing
I'm building a site using react and react-router.我正在使用 react 和 react-router 构建一个站点。 My site is split into two sections: front and partners section.
我的网站分为两个部分:前台和合作伙伴部分。 I want the partners section to be accessed using a subdomain
partner
.我希望使用子域
partner
访问 partners 部分。 I have written the following code since react-router does not support subdomain routing.我写了下面的代码,因为 react-router 不支持子域路由。 I'm unsure whether or not this is 'good practice'.
我不确定这是否是“良好做法”。 So my question is, is this a proper solution, if not, what are the alternatives?
所以我的问题是,这是一个合适的解决方案吗?如果不是,还有哪些替代方案?
<BrowserRouter>
<Route path="/" render={props => {
const [subdomain] = window.location.hostname.split('.');
if (subdomain === 'partner') return <PartnerLayout {...props}/>;
return <AppLayout {...props}/>;
}}/>
</BrowserRouter>
I don't use react-router, but the following should work if you just add react router jsx to the individual application components我不使用 react-router,但如果您只是将 react router jsx 添加到各个应用程序组件,则以下内容应该可以工作
import React from 'react';
import {MainApplication} from './Main';
function subdomainApplications (map) {
let main = map.find((item)=> item.main);
if (!main) {
throw new Error('Must set main flag to true on at least one subdomain app');
}
return function getComponent () {
const parts = window.location.hostname.split('.');
let last_index = -2;
const last = parts[parts.length - 1];
const is_localhost = last === 'localhost';
if (is_localhost) {
last_index = -1;
}
const subdomain = parts.slice(0, last_index).join('.');
if (!subdomain) {
return main.application;
}
const app = map.find(({subdomains})=> subdomains.includes(subdomain));
if (app) {
return app.application;
} else {
return main.application;
}
}
}
const getApp = subdomainApplications([
{
subdomains: ['www'],
application: function () {
return 'Main!'
}
main: true
},
{
subdomains: ['foo'],
application: function () {
return 'Foo!';
}
},
{
subdomains: ['bar', 'baz.bar'],
application: function () {
return 'Bar!';
}
}
]);
export default function Application () {
const App = getApp();
return (
<App className="Application" />
);
}
It's a good practice to treat primary domain code and sub domain code as different codebases.将主域代码和子域代码视为不同的代码库是一种很好的做法。 Also as you are aware and react-router is a client side module.
另外,正如您所知,react-router 是一个客户端模块。 Although this hack might work, it's generally frowned upon.
尽管这种 hack 可能有效,但通常不被接受。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.