反应路由器子域路由 [英] React-router subdomain routing
问题描述
我正在使用react和react-router建立一个站点.我的网站分为两部分:前台部分和合作伙伴部分.我希望使用子域 partner
访问partners部分.我写了以下代码,因为react-router不支持子域路由.我不确定这是否是好的做法".所以我的问题是,如果不是这样的话,这是一个适当的解决方案吗?
I'm building a site using react and 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
. I have written the following code since react-router does not support subdomain routing. 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>
推荐答案
我不使用react-router,但是如果您仅将react router jsx添加到各个应用程序组件中,则以下方法应该起作用
I don't use react-router, but the following should work if you just add react router jsx to the individual application components
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屋!