显示未找到React Router v4页面

时间:2018-08-28 13:26:36

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

我有两个组件,我想显示未找到的页面,但是问题是,我不想在NotFound内调用<switch>组件,因为我的开关在标题和侧边栏中。

请参阅组件代码。

App.js

import React, {Component} from 'react';
import Header from './Header.js';
import Main from './Main.js';
import { Switch, Route, Redirect } from 'react-router-dom';


class App extends Component
{
    constructor(){
    super();
}

render(){
    return (
        <Switch>
            <Route  path="/" component={Main} />
        </Switch>
    )
 }
}
export default App;

我的下一个组件Main.js

import React, {Component} from 'react';
import Header from '../app/Header.js'
import Integration from '../app/Integration.js';
import History from '../app/History';
import { Switch, Route } from 'react-router-dom'
import Dashboard from './Dashboard';
import List from '../config/List'
import NotFound from './NotFound';



class Main extends Component
{
constructor(){
    super();
}

render(){
    return (
        <div>
            <Header/>
            <div className="content">
                <History/>
                <div className="main-content">
                    <Switch>
                        <Route exact path="/configuration" component={List} />
                        <Route  exact path="/configuration/show" component={Dashboard} /> 
// I don't want to put my NotFound Route Tag here, because it includes header and sidebar */
                    </Switch>
                </div>
                <Integration/>
            </div>
        </div>
    )
 }
}
 export default Main

1 个答案:

答案 0 :(得分:0)

我已经解决了。

第1步:在主组件中创建了一个功能

renderWithLayout = (component) => {
    return (<div>
        <Header/>
        <div className="content">
            <History/>
            <div className="main-content">
                {component}
            </div>
            <Integration/>
        </div>
    </div>)
};

第二步:修改了主要组件的渲染方法

render(){
    return (
        <Switch>
            <Route exact path="/configuration" render={(props) => {
                return this.renderWithLayout(<List {...props}/>) ;
            }} />
            <Route  exact path="/configuration/show" render={(props)=>{
                return this.renderWithLayout(<Dashboard {...props}/>);
            }} />
            <Route path="*" component={NotFound}/>
        </Switch>
    )
}

无论如何。谢谢您的努力:)