ReactJS hide header on invalid page(404)

2019-08-05 08:21发布

问题:

I've recently started learning React and I've been trying to figure out how I would go about hiding my header when the user is trying to route to an invalid page/path. The only way I can think of is to manually add to each of my components and remove the from my App.js. For now I'm simply redirecting them to the home page. Below are my App and Root JS files. Before I had <Redirect to="/" />, I used <Route component={invalidPage}/> to link to an InvalidPage component, but couldn't figure out a way to hide the header.

//App.js
class App extends React.Component {
    render(){
        return(
            <Router>
                <Root>  
                    <Switch>
                        <Route exact path={"/"} component={Home}/>
                        <Route exact path={"/user"} component={User}/>
                        <Route exact path={"/home"} component={Home}/>      
                        <Redirect to="/"/>
                    </Switch>
                </Root>
            </Router>
        );
    }
}

//Root.js
export class Root extends React.Component{
    render(){
        return(
            <div className="container">
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                        <Header/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                        {this.props.children}
                    </div>
                </div>
            </div>
        );
    }
}

回答1:

Use Higher Order Components. This approach should basically work. Tell me if you face difficulties.

//App.js
class App extends React.Component {
  render(){
    return(
      <Router>
          <Switch>
            <Route exact path={"/"} component={withRoot(Home)}/>
            <Route exact path={"/user"} component={withRoot(User)}/>
            <Route exact path={"/home"} component={withRoot(Home)}/>
            <Route component={invalidPage}/>
          </Switch>
      </Router>
    );
  }
}

const withRoot= (Component)=> <Root><Component/></Root>