无法使用布局渲染反应组件

时间:2018-09-24 10:30:58

标签: javascript reactjs

我有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

3 个答案:

答案 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>