簡體   English   中英

ReactJS 路由頁面刷新

[英]ReactJS Routing Page Refresh

目前使用 ReactJS 構建一個小的 web 應用程序。 我有以下父 function:

    const Main = () => {
        return (
            <div className="dialog-base">
                <BrowserRouter>
                    <Switch>
                        <Route exact path="/login" component={Login}></Route>
                        <Route exact path="/login/forgot_password" component={ForgotPwd}></Route>
                        <Route exact path="/login/reset_password/:key" component={ResetPwd}></Route>
                        <Route exact path="/portal" component={Portal}></Route>
                    </Switch>
                </BrowserRouter>
            </div>
        );
     }

以下是“門戶”組件:

class Portal extends React.Component {
    render = () => {
        return (
            <BrowserRouter basename="/main">
                 <div className="navmenu">
                     <NavLink to="messaging" activeClassName="selected">Messaging</NavLink>
                     <NavLink to="files" activeClassName="selected"></NavLink>
                     <NavLink to="payledger" activeClassName="selected"></NavLink>
                 </div>
                 <div className="apparea">
                     <Switch>
                         <Route path="/messaging" component={Messaging}></Route>
                         <Route path="/files" component={Files}></Route>
                         <Route path="/payledger" component={PayLedger}></Route>
                     </Switch>
                 </div>
            </BrowserRouter>
        );
    }
}

加載門戶組件並刷新 web 頁面后,頁面變為空白。 我假設這與嵌套路由有關? 任何有關如何修復它的幫助將不勝感激。

您不需要兩個<BrowserRouter /> 只需在頂級組件中定義一個<BrowserRouter /> 在 react-router-dom v4+ 中, <Route />就像一個常規組件,當路徑與 URL 匹配時,您可以在組件內部使用它來呈現 UI。

這是工作代碼框示例 確保不要在您的父<Route />上放置exact內容,因為當您有像/main/messaging這樣的子路由時, <Route exact path="/main" />永遠不會渲染,因此該路由的子路由不能渲染也。

您保持<Main />組件不變,但從<Route path='/portal' />中刪除exact內容並更改<Portal />

class Portal extends React.Component {
  render = () => {
      return (
         <React.Fragment>
             <div className="navmenu">
                 <NavLink to="/portal/messaging" activeClassName="selected">Messaging</NavLink>
                 <NavLink to="/portal/files" activeClassName="selected"></NavLink>
                 <NavLink to="/portal/payledger" activeClassName="selected"></NavLink>
             </div>
             <div className="apparea">
                 <Switch>
                     <Route path="/portal/messaging" component={Messaging}></Route>
                     <Route path="/portal/files" component={Files}></Route>
                     <Route path="/portal/payledger" component={PayLedger}></Route>
                 </Switch>
             </div>
          </React.Fragment>
      );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM