reactrouter监听路由变化_监听history.push/replaceState和local/sessionStorage变化
时间: 2023-10-23 16:14:18 浏览: 158
React Router提供了一个高阶组件`withRouter`,可以将路由相关的属性和方法注入到组件props中。通过使用`withRouter`,我们可以监听路由变化。
下面是一个例子,展示如何监听`history.push`和`history.replace`方法的调用:
```jsx
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
componentDidMount() {
const { history } = this.props;
this.unlisten = history.listen((location, action) => {
if (action === 'PUSH') {
console.log('Pushed to ', location.pathname);
} else if (action === 'REPLACE') {
console.log('Replaced with ', location.pathname);
}
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return <div>My Component</div>;
}
}
export default withRouter(MyComponent);
```
要监听`localStorage`和`sessionStorage`的变化,可以使用`window.addEventListener`方法:
```jsx
window.addEventListener('storage', (event) => {
if (event.storageArea === localStorage) {
console.log('localStorage changed');
} else if (event.storageArea === sessionStorage) {
console.log('sessionStorage changed');
}
});
```
需要注意的是,在同一浏览器窗口或标签页中,`localStorage`和`sessionStorage`的变化是共享的,因此如果在同一浏览器窗口或标签页中打开了多个相同的页面,一个页面的`localStorage`或`sessionStorage`的变化会影响到其他页面。
阅读全文