當路由發生變化時,有沒有什麼辦法可以觸發路由器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路由器V4結構
- 5. React路由器和onEnter/onChange
- 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路由器和路由參數
- 16. React路由器路由通過?
- 17. Browserify + WebStorm調試在React-Router v4中斷了路由瀏覽器路由器
- 18. React路由器v4與路由器一起使用時拋出PropTypes錯誤
- 19. React路由器v4.1.1
- 20. React-Router v4添加子路由
- 21. React Router v4 - 嵌套路由問題
- 22. React-router v4路由點擊按鈕
- 23. ReactJS和嵌套路由與react-router v4
- 24. React路由器v4呈現多條路線
- 25. React路由器v4 - 動態嵌套路徑
- 26. React路由器與React v0.14.3
- 27. React路由器v4等待xhr身份驗證過渡到路由
- 28. 反應路由器V4路徑問題
- 29. React路由器V4更新URL但不刷新(React,Redux)
- 30. 反應路由器v4 - 登錄路由器主頁
新的V4 API不再具有'onEnter'方法,所以在這裏不起作用。 – Dennis