我有Navbar
,必须在每个页面上进行渲染。所以我正试图通过BrowserRouter来获得它,像这样:
import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import PublicLayout from './components/layouts/PublicLayout';
import Main from './components/pages/Main';
import Services from './components/pages/Services';
class App extends Component {
render() {
return (
<BrowserRouter>
<div className="App">
<Route component={ PublicLayout }>
<Route exact path='/' component={ Main } />
<Route exact path='/services' component={ Services } />
</Route>
</div>
</BrowserRouter>
);
}
}
export default App;
我的PublicLayout只是导航链接。我在屏幕上看到它。但是React不会渲染Main page
的内容。我希望能从Navbar下面的Main page组件中看到Hello World。我做错了什么?请帮忙。
UPD:我的PublicLayout代码:
import React, { Component } from 'react';
import Navbar from '../nav/Navbar';
class PublicLayout extends Component {
state = {
items: [
{ id: 1, name: 'Услуги', link: '/services' },
]
}
render() {
return (
<div>
<Navbar items={ this.state.items } />
{ this.props.children }
</div>
);
}
}
export default PublicLayout;
UPD2::在浏览器控制台中,我看到一个错误:
Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored
答案 0 :(得分:0)
不确定自己为什么使用PublicLayout
,不能在Route
内使用Route
。
在PublicLayout
中创建BrowserRouter
作为子项。
`
<BrowserRouter>
<div className="App">
<Route exact path="/" component={Main} />
<Route exact path="/services" component={Services} />
</div>
</BrowserRouter>
答案 1 :(得分:0)
找到了答案here。由于React v4可以包装组件,因此您不再将Routes放置在另一个Route中,因此可以将Routes直接放置在组件中。
<Router>
<MyLayout>
<Route path='/abc' component={ABC} />
<Route path='/xyz' component={XYZ} />
</MyLayout>
</Router>
答案 2 :(得分:0)
将<Route component={ PublicLayout }>
替换为<PublicLayout>
<PublicLayout>
<Route exact path='/' component={ Main } />
<Route exact path='/services' component={ Services } />
</PublicLayout>