我很反应路由。阅读完文档并阅读一些文章后,这就是我的路由结构。如果我做错了,请纠正我。
使用react-router V4
Routes.js
import React from 'react';
import App from '../app/components/App';
import Dashboard from '../dashboard/components/Dashboard';
import Contact from '../dashboard/components/Contact';
import Account from '../dashboard/components/Account';
import Career from '../dashboard/components/Career';
import NoMatch from './NoMatch';
import { Provider } from 'react-redux';
import { Route, BrowserRouter, Switch, Redirect } from 'react-router-dom';
const Root = ({ store }) => (
<Provider store={store}>
<BrowserRouter>
<div>
<Route path="/app" component={App} />
<Switch>
<Route path="/app" exact component={Dashboard} />
<Route path="/app/home/dashboard" component={Dashboard} />
<Route path="/app/home/contact" component={Contact} />
<Route path="/app/home/account" component={Account} />
<Route path="/app/home/career" component={Career} />
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
</Provider>
)
export default Root
我使用/ app 2次。首先是加载,因为它有sidenav和header。然后在内部开关我用来加载默认组件仪表板。
App.js
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import 'font-awesome/css/font-awesome.min.css';
import Header from './Header';
import SideNav from './SideNav';
class AppComp extends Component {
componentDidMount() {
const { match: { params } } = this.props;
}
render() {
return (
<div>
<div className="container body">
<div className="main_container">
<Header />
<SideNav routeparams={this.props}/>
</div>
</div>
</div>
);
}
}
export default AppComp;
Sidenav.jsx
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom'
import '../../css/sidenav.css';
class SideNav extends Component {
render() {
console.log(this.props.routeparams);
return (
<div className="col-md-3 left_col">
<div className="left_col">
<div className="clearfix"></div>
<div id="sidebar-menu">
<div className="menu">
<ul className="nav side-menu">
<li>
<NavLink to="/app/home/dashboard">Home</span></NavLink>
<ul>
<li className="current-page">
<NavLink to="/app/home/dashboard" activeClassName="current">Dashboard</NavLink>
</li>
<li>
<NavLink to="/app/home/contact" activeClassName="current">Contact</NavLink>
</li>
<li>
<NavLink to="/app/home/account" activeClassName="current">Account</NavLink>
</li>
<li>
<NavLink to="/app/home/career" activeClassName="current">Career</NavLink>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
);
}
}
export default SideNav;
我有两个问题:
side.av中的this.props.routeparams记录了两次,这意味着sidenav渲染了两次。添加路由后会发生这种情况。另外this.props.routeparams匹配路径总是/ app,我认为因为sidenav是app组件的子组件。我怎样才能解决这个问题 ?我想在sidenav中获取当前路径路径。
activeClassName =&#34;电流&#34;应用于更正navlink,但只有当我点击页面中的某个地方时才会反映css样式。好像很奇怪。我可以解决这个问题,如果我在sidenav组件中获得当前match.path然后我将自定义方式而不使用activeClassName。
非常感谢任何帮助。