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