【问题标题】:redirecting on route component , without having the header and footer component在路由组件上重定向,没有页眉和页脚组件
【发布时间】:2018-11-05 11:58:37
【问题描述】:

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

我可以重定向,但每当我重定向页眉和页脚组件时都会出现。因为我在页眉和页脚之间调用路由组件。那么我怎样才能只显示文本 Redirecting 没有页眉和页脚组件

   <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


    【解决方案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 的高堆栈顺序,以及其他必要的样式以用白色背景覆盖整个屏幕;因此它应该显示在周围所有其他元素的前面。此外,还需要一个带有“位置:相对”的外部“包装器”div 才能使其工作。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      您需要将&lt;Header&gt;&lt;Footer&gt; 包装到您的每个页面AboutUsContactHomePage

      没有其他方法可以在父级别有条件地呈现&lt;Header&gt;&lt;Footer&gt;,除非您想在父级别维护一个控制是否显示页眉和页脚的状态,这不是一个理想的解决方案。

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

      【讨论】:

      • 所以对于这个,我们没有解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      相关资源
      最近更新 更多