我有3种类型的用户,当大多数视图仅取决于用户类型时,我们希望为项目维护相同的代码库,而不是3-4个代码库。
管理员> admin.example.com
主持人> moderator.example.com
Brands> brand.example.com
我的React App的结构
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中,您可以使用该简单逻辑,以便仅呈现特定角色的路由:
<Router history={history}>
{isAdmin &&
<Route component={AdminViews} />
}
{isModerator &&
<Route component={ModeratorViews} />
}
...
<Route path="/tnc" exact={true} component={CommmonRouteForAllRoles} />
</Router>
例如AdminViews可能看起来像这样:
export const AdminViews = () => {
return (
<Switch>
<Route path="/" exact={true} component={AdminHome} />
<Route path="/other" exact={true} component={AdminOtherRoute} />
<Route path="/sign-in" exact={true} component={AdminSignIn} />
</Switch>
);
};