簡體   English   中英

react-router v3:進入和離開特定路線時如何重新加載頁面

[英]react-router v3: how to reload page when entering and leaving a specific route

我有一個單頁應用程序的特定路由,我希望在用戶進入或離開此路由時使頁面完全重新加載。

    <Route
      key={routeKeyGen()}
      path="/example"
      component={Example}
      onEnter={onExampleRoute}
    />

我試圖通過設置onEnter來刷新瀏覽器頁面來做到這一點:


const onExampleRoute = () => window.location.reload();

當頁面一遍又一遍地重新加載時,我很快意識到這很荒謬。 我也不認為這在離開路線時會處理。

編輯這里是用於Route的 React Router v3 API: https : //github.com/ReactTraining/react-router/blob/v3/docs/API.md#route

編輯 2 :React Router v3 API 中有一個onLeave for Routehttps : //github.com/ReactTraining/react-router/blob/v3/docs/API.md#onleaveprevstate

使用純 React 的最簡單解決方案可以是:

在路由的組件中以編程方式加載腳本

如果這是您的route.js文件

<Route path="/path/you/want/to/load/js" component={Page.js} />

Page.js組件中:

class Page extends Component {

   ...

   componentDidMount () {
      const script = document.createElement("script");

      script.src = "https://path/to/your/file.js";
      script.async = true;
      script.onload = this.handleScriptLoad;

      document.body.appendChild(script);
   }

   handleScriptLoad = () => {
      // the script loaded!!!
   }

   ...
}

有關更多詳細信息,您可以查看此處: 向 React/JSX 添加腳本標記

暫無
暫無

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

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