当路由发生变化时,有没有什么办法可以触发路由器v4。我需要在每个路线变化上开启一个功能。我在客户端使用和Switch
,从react-router-dom
开始使用universal react-redux应用程序。React路由器v4路由onchange事件
2
A
回答
3
我解决了这个问题,用附加组件包装了我的应用程序。该组件用于Route
,因此它也可以访问history
道具。
<BrowserRouter>
<Route component={App} />
</BrowserRouter>
的App
组件订阅历史的变化,所以我可以做什么,只要路由变化:
export class App extends React.Component {
componentWillMount() {
const { history } = this.props;
this.unsubscribeFromHistory = history.listen(this.handleLocationChange);
this.handleLocationChange(history.location);
}
componentWillUnmount() {
if (this.unsubscribeFromHistory) this.unsubscribeFromHistory();
}
handleLocationChange = (location) => {
// Do something with the location
}
render() {
// Render the rest of the application with its routes
}
}
不知道这是做在V4以正确的方式,但我没有”在路由器本身上找到任何其他可扩展性点,所以这似乎可以工作。希望有所帮助。
编辑:也许你也可以实现相同的目标,将<Route />
包装在你自己的组件中,并使用类似componentWillUpdate
的东西来检测位置变化。
+1
当我需要更改状态更改路线时,是否可以使用历史包中的history.createBrowserHistory方法? –
+1
@丹尼斯这不是我所期望的,但我很满意,谢谢 – JoxieMedina
0
阵营:v15.x,阵营路由器:4.x版
组件/核心/ App.js:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter } from 'react-router-dom';
class LocationListener extends Component {
static contextTypes = {
router: PropTypes.object
};
componentDidMount() {
this.handleLocationChange(this.context.router.history.location);
this.unlisten =
this.context.router.history.listen(this.handleLocationChange);
}
componentWillUnmount() {
this.unlisten();
}
handleLocationChange(location) {
// your staff here
console.log(`- - - location: '${location.pathname}'`);
}
render() {
return this.props.children;
}
}
export class App extends Component {
...
render() {
return (
<BrowserRouter>
<LocationListener>
...
</LocationListener>
</BrowserRouter>
);
}
}
index.js:
import App from 'components/core/App';
render(<App />, document.querySelector('#root'));
相关问题
- 1. 反应路由器v4路由事件
- 2. React路由器v4并行路由
- 3. React路由器V4结构
- 4. React路由器和onEnter/onChange
- 5. React路由器v4不显示组件
- 6. React路由器V4,未找到组件
- 7. React路由器v4阻止匹配子路由
- 8. React路由器v4 - 重定向
- 9. React路由器OnChange重定向
- 10. Typescript React React-Router V4不能路由
- 11. react - 路由器与路由器不注入路由器
- 12. React路由器V4 - 组件之间的路由而不是整个页面
- 13. react路由器:客户端路由与服务器端路由
- 14. React路由器 - 动态路由设置
- 15. React路由器v4与路由器一起使用时抛出PropTypes错误
- 16. Browserify + WebStorm调试在React-Router v4中断了路由浏览器路由器
- 17. React路由器v4.1.1
- 18. React-Router v4添加子路由
- 19. React-router v4路由点击按钮
- 20. React Router v4 - 嵌套路由问题
- 21. ReactJS和嵌套路由与react-router v4
- 22. React路由器v4 - 动态嵌套路径
- 23. 反应路由器V4路径问题
- 24. React路由器v4等待xhr身份验证过渡到路由
- 25. 反应路由器v4 - 登录路由器主页
- 26. React路由器V4更新URL但不刷新(React,Redux)
- 27. 反应路由器V4子组件
- 28. React路由器v4渲染组件内部元素
- 29. React路由器Dom V4验证检查来渲染组件
- 30. 作出反应路由器v4中的异步路由的私有路由
新的V4 API不再具有'onEnter'方法,所以在这里不起作用。 – Dennis