[英]React-router subdomain routing
我正在使用 react 和 react-router 构建一个站点。 我的网站分为两个部分:前台和合作伙伴部分。 我希望使用子域partner
访问 partners 部分。 我写了下面的代码,因为 react-router 不支持子域路由。 我不确定这是否是“良好做法”。 所以我的问题是,这是一个合适的解决方案吗?如果不是,还有哪些替代方案?
<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 添加到各个应用程序组件,则以下内容应该可以工作
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" />
);
}
将主域代码和子域代码视为不同的代码库是一种很好的做法。 另外,正如您所知,react-router 是一个客户端模块。 尽管这种 hack 可能有效,但通常不被接受。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.