重定向路由组件,没有页眉和页脚组件

问题描述 投票:0回答:2

我有一个示例应用程序,每当我加载根URL时,我正在检查cookie是否有效,如果cookie在那里,那么我加载主页组件,我需要重定向到外部URL。

我能够重定向,但每当我重定向页眉和页脚组件出现。因为我在页眉和页脚之间调用路径组件。那么我怎样才能显示没有页眉和页脚组件的重定向文本

   <BrowserRouter> 
    <Header />
    <div className="content">
       <Route path="/aboutus" component={AboutUs} />
       <Route path="/contact" component={Contact} />
       <Route path="/" render ={() => {
         // checking the cookie exists
         if(cookieExists){
           return (<HomePage />)
        }else{
        axios.get("api/userLoggedIn")
            .then(res => {
          // the url is an external url [https://www.examplelogin.com]
          window.location.assign(res.data);
        })
         .catch(err => console.log("error in api", err))
        return <div>Redirecting</div>;
        }
       }}
     />
    </div>
    <Footer />
    </BrowserRouter>
reactjs react-router
2个回答
1
投票

我想你可以在'div'标签上使用以下样式,如下所示:

const contact = {zIndex: 9999, backgroundColor: "#fff", top: 0, right: 0, left: 0, bottom: 0, position: "absolute"};
const wrapper = {position: "relative"}; 

<BrowserRouter>
  <div style={wrapper}>
    <Header />
    <div className="content">
       <Route path="/aboutus" component={AboutUs} />
       <Route path="/contact" component={Contact} />
       <Route path="/" render ={() => {
         // checking the cookie exists
         if (cookieExists){
           return (<HomePage />)
         } else {
           axios.get("api/userLoggedIn")
           .then(res => {
             // the url is an external url [https://www.examplelogin.com]
             window.location.assign(res.data);
           })
           .catch(err => console.log("error in api", err))
           return <div style={contact}>Redirecting</div>;
         }
       }}/>           
    </div>
  </div>
</BrowserRouter>

“重定向”div已经通过zIndex给出了高堆栈顺序,以及其他必要的样式以覆盖整个屏幕的白色背景;因此它应该显示在周围所有其他元素的前面。此外,需要一个带有“position:relative”的外部“包装”div来使其工作。

希望这可以帮助。


0
投票

你需要将<Header><Footer>包装到你的每一页AboutUsContactHomePage中。

没有其他方法可以在父级别有条件地渲染<Header><Footer>,除非你想在父级别维持一个状态来控制是否显示Header和Footer这不是一个理想的解决方案。

只需将它们包装到每个组件中 - AboutUsContactHomePage

© www.soinside.com 2019 - 2024. All rights reserved.