我在主组件中定义了一个路由器。 我想通过react路由器在此主要组件中渲染组件。 每次渲染任何Route时,我都希望在Navbar上也渲染主组件。 我该如何路由它们?
方法1:
import React, { Component } from 'react';
import './App.css';
import { Provider } from 'react-redux';
import store from './store';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Main from './actions/sidebartoggleActions'
import FirstDashboard from './_layouts/views/firstDashboard';
import SecondDashboard from './_layouts/views/secondDashboard';
import ThirdDashboard from './_layouts/views/thirdDashboard';
import FourthDashboard from './_layouts/views/fourthDashboard';
class Main extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div>
<Route path='/' exact strict component={Main} />
<Route path='/overview1' exact strict component={FirstDashboard} />
<Route path='/overview2' exact strict component={SecondDashboard} />
<Route path='/overview3' exact strict component={ThirdDashboard} />
<Route path='/overview4' exact strict component={FourthDashboard} />
</div>
</Router>
</Provider>
);
}
}
export default Main;
方法2:
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import store from './store';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './actions/sidebartoggleActions'
import FirstDashboard from './_layouts/views/firstDashboard';
import SecondDashboard from './_layouts/views/secondDashboard';
import ThirdDashboard from './_layouts/views/thirdDashboard';
import FourthDashboard from './_layouts/views/fourthDashboard';
class Main extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div>
<App />
<Route path='/overview1' exact strict component={FirstDashboard} />
<Route path='/overview2' exact strict component={SecondDashboard} />
<Route path='/overview3' exact strict component={ThirdDashboard} />
<Route path='/overview4' exact strict component={FourthDashboard} />
</div>
</Router>
</Provider>
);
}
}
export default Main;
答案 0 :(得分:0)
<Router>
<div>
<Header />
<Route path='/' exact strict component={Main} />
<Route path='/overview1' exact strict component={FirstDashboard} />
<Route path='/overview2' exact strict component={SecondDashboard} />
<Route path='/overview3' exact strict component={ThirdDashboard} />
<Route path='/overview4' exact strict component={FourthDashboard} />
</div>
</Router>
应该没问题。这样做可以确保无论使用哪种路由,该路由始终位于标题下方。
答案 1 :(得分:0)
我找到了解决方案,将Routes嵌套在Component内,然后在Index component内调用{props.this.children},解决了我的问题。 我是指-https://github.com/reactjs/react-router-tutorial/tree/master/lessons/04-nested-routes
const Main = () => (
<Provider store={store}>
<Router>
<Switch>
<Index>
<Route path='/overview1' component={FirstDashboard} />
<Route path='/overview2' component={SecondDashboard} />
<Route path='/overview3' component={ThirdDashboard} />
<Route path='/overview4' component={FourthDashboard} />
</Index>
</Switch>
</Router>
</Provider>
)
export default Main;