簡體   English   中英

React-router 子域路由

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM