如何解决嵌套路由在 react-router-dom
我已经使用 react-router-dom 配置了我的路由,并用 <HashRouter/>
包装了我的渲染应用程序。
在我的路线中,我定义了多条路线,并且有一些奇怪的问题可能我无法解决,即存在路径 /accounts
的地方工作正常,但是如果我使用 /accounts/manage_account
定义路线, /accounts/create/
或 /accounts/:uniqueId
作为子节点,则路由未呈现正确的组件。
我被困在这里的实际问题是什么。我很感激任何人在这方面的帮助
*routes.js*
import React from 'react'
import {Router,Switch,Route,Redirect} from "react-router-dom";
import history from 'routers/history'
import UISidebarTabsUtil from 'utils/ui_sidebar_tabs_util';
import {UI_CONSTANTS} from 'utils/globals';
import {Authorization,requireAuth} from 'auth/authorization';
import CDashboard from 'containers/dashboard/c_dashboard';
import CResourceAccessDetail from 'containers/dashboard/c_resource_detail';
//discovery
import CScanRequest from 'containers/configuration/application/c_scan_request';
//Data-Inventory
import CDataClassification from 'containers/discovery/c_data_classification';
// import CDataDetail from 'containers/discovery/c_data_detail';
import CAccessDetail from 'containers/dashboard/c_access_detail';
import CAccounts from 'containers/account/c_accounts';
import CAccountForm from 'containers/account/c_account_form';
import CManageTenant from 'containers/account/c_manage_tenant';
import CBillingDashboard from 'containers/billing_usage/c_billing_usage'
import CAssumeRole from 'containers/assume_role/c_assume_role';
import CScheme from 'containers/crypto/scheme/c_scheme';
import CReporting from 'containers/reports/c_reporting';
import CSavedReportListing from 'containers/reports/c_saved_report_listing';
// import COfflineReports from 'containers/reports/c_offline_reports';
import CAuditsMain from 'containers/audits/c_audits_main';
import CUserManagementMain from 'containers/user_management/c_user_management_main';
import CLDapRoleMapping from 'containers/user_management/c_ldap_role_mapping';
import CPageNotFound from 'containers/c_page_not_found';
import CForbiddenError from 'containers/c_forbidden_error';
import CApiKey from 'containers/api_key/c_api_key';
import CSystemApplications from 'containers/data_source_registration/c_system_application'
import CReportStatistics from 'containers/c_report_statistics';
// cloud acccess manager
// import CLaunchPad from 'containers/cloud_manager/c_launch_pad';
import CAWSCLI from 'containers/cloud_manager/c_aws_cli';
import ccloudTokens from 'containers/cloud_manager/c_cloud_tokens';
//<Route path="tokens" name="JWT Tokens" component={Authorization(CUserTokens,""/*[UI_CONSTANTS.SETTINGS,UI_CONSTANTS.TOKENS]*/,() => !UISidebarTabsUtil.isPortalUserTokenEnable())} />
const Routes = () => (
<div>
<Switch>
<Redirect exact path="/" name="Home" to={"account"} />
<Route exact path="/" component={Authorization(CDashboard,[UI_CONSTANTS.DASHBOARD])} />
<Route exact path="/account" render = {({...props}) => (
<Switch>
<Route path={`${props.match.path}`} name="Account" component={Authorization(CAccounts,[UI_CONSTANTS.SETTINGS,UI_CONSTANTS.ACCOUNTS])} />
<Route path={`${props.match.path}/create`} name="Create Account" component={Authorization(CAccountForm,UI_CONSTANTS.ACCOUNTS])} />
<Route path={`${props.match.path}/:accountUniqueId`} getdisplayName={() => "Account Info"} component={Authorization(CAccountForm,UI_CONSTANTS.ACCOUNTS])} />
<Route path={`${props.match.path}/manage`} name="Manage Account" component={Authorization(CManageTenant,[UI_CONSTANTS.DASHBOARD])} />
</Switch>
)}>
</Route>
<Route path="/api_key" getdisplayName={() => "Api Key"} component={Authorization(CApiKey,UI_CONSTANTS.API_KEY])} />
<Route path="/dashboard" name="Dashboard" component={Authorization(CDashboard,[UI_CONSTANTS.DASHBOARD])} />
</Switch>
</div>
)
export {
Routes
}
********************root.js*********************
import {hot} from 'react-hot-loader';
import React,{Component} from 'react';
import {reaction} from 'mobx';
import {Provider} from 'mobx-react'
import { withRouter } from "react-router";
// import {Router,hashHistory} from 'react-router';
import NotificationSystem from 'react-notification-system';
// import Promise from 'bluebird';
import DevTools from 'mobx-react-devtools';
import ReactGA from 'react-ga';
import {Confirm} from 'lib/fs_modal';
import {Routes} from 'routers/routes';
import f from 'utils/f';
import UiState from 'data/ui_state'
import {configProperties} from 'utils/config_properties';
import * as buildVersion from '../../privacera_version';
// import "pdfmake/build/pdfmake";
// import PDFUtil from 'utils/pdf_util';
import 'lib/timezone_worldmap/timezone_worldmap';
/*if (PDFUtil && PDFUtil.loadFonts) {
PDFUtil.loadFonts();
}*/
class Root extends Component {
constructor(props) {
super(props);
UiState.setBuildVersion(buildVersion);
reaction(
() => UiState.refreshProps,() => {
if (UiState.refreshProps) {
this.refresh();
}
}
)
reaction(
() => UiState.switchRole,() => {
if (UiState.switchRole) {
this.setState({loaded: false});
// this.fetch();
this.refresh();
}
}
)
}
state = {
loaded: false
}
async fetch() {
try {
const load = await UiState.fetch();
this.setState({loaded: true});
this.loadFeedBackTool();
this.loadInstana();
this.initGA(load);
UiState.setSwitchRoleProps(false);
} catch(e) {
console.log(e);
UiState.logout();
}
}
async refresh() {
const { history: hashHistory } = this.props
this.setState({loaded: false});
try {
const load = await UiState.refreshProperties();
hashHistory.push('/')
this.setState({loaded: true});
UiState.setRefreshProps(false);
UiState.setSwitchRoleProps(false);
} catch(e) {
this.setState({loaded: true});
UiState.setRefreshProps(false);
UiState.setSwitchRoleProps(false);
}
}
componentDidMount() {
this.fetch();
f.setNotificationSystem(this.refs.notificationSystem);
f.setConfirmBox(this.refs.confirm);
}
initGA = (userData={}) => {
const { history: hashHistory } = this.props
let id = configProperties.getGoogleAnalyticsId();
if (!id) {
return;
}
ReactGA.initialize(id);
hashHistory.listen(location => {
const {pathname} = location;
ReactGA.set({
page: pathname,userId : userData.accountUniqueId,location : `${window.location.origin}${pathname}`
});
ReactGA.pageview(pathname);
});
}
loadFeedBackTool = () => {
// UiState.userAccountID()
/*
window.onusersnapCXLoad = function(api) {
api.init();
}
var script = document.createElement('script');
script.async = 1;
script.src = 'https://widget.usersnap.com/load/52b2b363-f383-4eea-916d-9e8212722b73?onload=onusersnapCXLoad';
document.getElementsByTagName('head')[0].appendChild(script);
*/
let FeedBackApiKey = UiState.getFeedBackApiKey();
if (!FeedBackApiKey) {
return;
}
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
s.src = `//api.usersnap.com/load/${FeedBackApiKey}.js`;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s,x);
}
loadInstana = () => {
let reportingUrl = configProperties.getInstanaReportingUrl();
let key = configProperties.getInstanaKey();
if (!reportingUrl && !key) {
return;
}
var s = document.createElement("script");
s.type = "text/javascript";
s.defer
s.crossorigin = "anonymous"
s.src = `https://eum.instana.io/eum.min.js`;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s,x);
(function(s,t,a,n) {
s[t] || (s[t] = a,n = s[a] = function() {
n.q.push(arguments)
},n.q = [],n.v = 2,n.l = 1 * new Date)
})(window,"InstanaEumObject","ineum");
ineum('reportingUrl',reportingUrl);
ineum('key',key);
ineum('trackSessions');
}
render() {
const {state} = this;
const {stores={}} = this.props;
return (
<Provider { ...stores }>
<div>
{/* state.loaded &&
<Router history={hashHistory} routes={routes} onUpdate={() => window.scrollTo(0,0)} />
*/}
{ state.loaded && <Routes /> }
<NotificationSystem ref="notificationSystem" />
<Confirm ref="confirm" />
{/* <DevTools /> */}
</div>
</Provider>
)
}
}
export default hot(module)(withRouter(Root));
************main.js**********
import React,{Component} from 'react'
import {render} from 'react-dom';
import { HashRouter } from 'react-router-dom';
import 'import_common_files';
import routes from 'routers/routes';
import stores from 'data/stores/all_stores';
import Root from 'root';
render(
<HashRouter>
<Root stores={stores} routes={routes} />
</HashRouter>,document.getElementById('main_region'));
提前致谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。