【发布时间】:2020-09-05 03:15:00
【问题描述】:
我有 3 种类型的用户,我们希望为项目维护相同的代码库,而不是拥有 3-4 个代码库,因为大多数观点只是对用户类型的主观判断。
管理员 > admin.example.com
版主 > moderator.example.com
品牌 >brands.example.com
我的 React 应用程序结构
src
-BaseRoutes.js <--- Should handle by subdomain logic
- modules
-- admin
---- AdminRoutes.js <---- handles all Admin route logic
---- components
---- pages
-- moderator
---- ModeratorRoutes.js <---- handles all Moderator route logic
---- components
---- pages
-- brands
---- BrandsRoutes.js <---- handles all Brands route logic
---- components
---- pages
- components
- pages
每种类型的用户都有自己的身份验证,以允许访问内部路由。我找到了一个功能来分割域并使用以下方法进行路由:
let host = window.location.host;
let protocol = window.location.protocol;
let parts = host.split(".");
let subdomain = "";
// If we get more than 3 parts, then we have a subdomain
// INFO: This could be 4, if you have a co.uk TLD or something like that.
if (parts.length >= 3) {
subdomain = parts[0];
// Remove the subdomain from the parts list
parts.splice(0, 1);
// Set the location to the new url
window.location = protocol + "//" + parts.join(".") + "/" + subdomain;
}
这是在 React 中处理基于子域的路由的正确方法吗?我从来没有为多种用户类型使用过一个代码库。对正确的实现感到困惑。
【问题讨论】:
-
你用的是什么路由器?你应该看看 React Router,reacttraining.com/react-router
-
@Joshua Am 使用相同的。但是在子域上没有找到任何帮助。
-
这听起来像是
client/react-router不会处理的事情,而是由您的 SPA 所在的服务器处理。假设所有三个子域都服务于相同的React代码库,我建议您从上面发布的代码中找出子域是什么,并有条件地渲染不同的组件,即如果它是admin,则仅显示渲染admin-specific routes/链接/导航等... -
@goto1 你是对的。有什么建议吗?
-
@HarshaMV 我已经实现了一次你想要实现的目标,但我无法再访问代码库来给你一些例子。创建一个全局路由器,即 BaseRouter,然后管理员、主持人等应该拥有自己的路由器。更像是带有子路由器的路由器。然后,您可以为每个路由添加身份验证。
标签: javascript reactjs react-router subdomain