gpt4 book ai didi

javascript - React-router子域路由

转载 作者:行者123 更新时间:2023-12-03 13:08:43 31 4
gpt4 key购买 nike

我正在使用react和react-router构建一个网站。我的网站分为两个部分:前端部分和合作伙伴部分。我希望使用子域 partner 访问合作伙伴部分。由于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" />
);
}

关于javascript - React-router子域路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45090243/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com