ReactJS在无效页面上隐藏标题(404) [英] ReactJS hide header on invalid page(404)

查看:82
本文介绍了ReactJS在无效页面上隐藏标题(404)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习React,我一直试图弄清楚当用户试图路由到无效页面/路径时如何隐藏标题.我能想到的唯一方法是手动添加到每个组件,然后从App.js中删除它.现在,我只是将它们重定向到主页.以下是我的App和Root JS文件.在使用<Redirect to="/" />之前,我曾使用<Route component={invalidPage}/>链接到InvalidPage组件,但找不到隐藏标题的方法.

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>
        );
    }
}

推荐答案

使用高阶组件.这种方法基本上应该起作用.告诉我你是否遇到困难.

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>

这篇关于ReactJS在无效页面上隐藏标题(404)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆