react-router子域路由

IT技术 javascript reactjs react-router
2021-04-11 01:45:10

我正在使用 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>
2个回答

我不使用 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 是一个客户端module。虽然这个黑客可能会奏效,但它通常是不受欢迎的。

完全不同意。没有理由单个 SPA 不应该跨多个子域工作,而且经常有需要的情况,例如虚荣子域,即。*.tumblr.com
2021-06-21 01:45:10