在react-router v4中的嵌套路由中看到空白页

时间:2019-01-04 22:18:18

标签: javascript reactjs react-router-v4 react-router-dom

我是新来的反应者,仍然在学习。 我正在尝试在我的react项目中添加嵌套的路由,以便div的内容根据该路由而变化。

以下是我的组件:-

//index.js

import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

library.add(faIgloo);

ReactDOM.render(<BrowserRouter>
  <App />
</BrowserRouter>, document.getElementById('root'));

serviceWorker.unregister();


// app.js
import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Login from './components/login/login.js'
import Protected from './components/protected/protected.js'



import './App.css';

class App extends Component {

  render() {
    return (
        <Switch>
          <Route exact path="/protected" component={Protected}/>
          <Route path="/login" component={Login}/>
        </Switch>
    );
  }
}

export default App;



//protected.js

import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from './header/header.js';
import './protected.css';

import CafePreview from './cafepreview/cafepreview.js'

class Protected extends Component {
  render() {
    const {match} = this.props;
    return (
        <div>
          <Header></Header>
          {/*<Preview/>*/}
          <Switch>
           <Route path='/protected/cafepreview' component={CafePreview}/>
          </Switch>
        </div>
    );
  }
}

export default Protected

// cafepreview.js

import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import './preview.css';

console.log("here");
class CafePreview extends Component {
  render() {
    return (
        <div>
           <div>
             <i class="fa fas fa-arrow-left"></i>
             <span> BACK TO ALL CAFES </span>
           </div>
        </div>
    );
  }
}

export default CafePreview

当我打开“ / protected”时,我可以看到标题即将到来,但是当我尝试打开“ / protected / cafepreview”时,我看到的是空白页面,而不是带有咖啡馆预览html的标题。

我尝试了这个stackoverflow线程Multiple Nested Routes in react-router-dom v4中提到的一些选项,但没有一个起作用。

我希望我已经清楚地解释了我的问题。

1 个答案:

答案 0 :(得分:0)

查看文档https://reacttraining.com/react-router/web/api/Route/exact-bool。从App组件中的路由中删除exact,它将开始起作用。