javascript - react 路由器 v3 : how to reload page when entering and leaving a specific route

标签 javascript reactjs react-router

我有一个单页面应用程序的特定路由,我希望每当用户进入或离开此路由时,页面都会完全重新加载。

    <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用于Route:https://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!!!
   }

   ...
}

欲了解更多详情,您可以看这里: Adding script tag to React/JSX

关于javascript - react 路由器 v3 : how to reload page when entering and leaving a specific route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59861318/

相关文章:

javascript - Javascript 中 for...of 循环和执行上下文中的解构赋值

node.js - 为什么我收到的 jwt 格式错误?

javascript - react 路由器 : state variable updated with setState not being passed down to Route correctly

javascript - 更改 AngularJS 开始和结束标签

javascript - jQuery .remove 不是函数

reactjs - Redux state props 值未定义

javascript - Strapi 自定义路由重定向到公共(public)目录

javascript - react 路由器状态?

javascript - 取消绑定(bind)与 .live() jQuery 绑定(bind)的事件

javascript - 如何实现React Router SPA的滚动恢复